Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205278

r - Having trouble applying a function to a vector

$
0
0

Still pretty new to R, so I'm not sure what I'm doing`wrong. I'm trying to apply this function to a vector in order to calculate % residual based on a starting value:

residual <- function(vec, offset, lngth){

 denom <- 1
 res_vec <- NULL
 for (i in 1:lngth){    

     if(i == 1 | i %% (offset) != 0)
{
         x <- vec[i] * 100/vec[denom]
         res_vec <- append(res_vec, x)
}

     else
{
         denom <- denom + offset
         x <- vec[i] * 100/vec[denom]
         res_vec <- append(res_vec, x)
}

}

res_vec
}

I'm using sapply. For example, if my vector is:

dv <- c(88, 84, 80, 90, 88, 85)

And I use sapply

x <- sapply(dv, residual, offset = 3, lngth = 6)

I'd like to get this vector:

100, 95, 91, 100, 98, 94

But instead I'm either getting this:

         [,1] [,2] [,3] [,4] [,5] [,6]
[1,]  100  100  100  100  100  100
[2,]   NA   NA   NA   NA   NA   NA
[3,]   NA   NA   NA   NA   NA   NA
[4,]   NA   NA   NA   NA   NA   NA
[5,]   NA   NA   NA   NA   NA   NA
[6,]   NA   NA   NA   NA   NA   NA

Is there something wrong with my function, or am I doing something wrong when trying to call it? I've gotten it to work fine in C++.

Thanks!


Viewing all articles
Browse latest Browse all 205278

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>