[R] help with for loop

Gabor Grothendieck ggrothendieck at gmail.com
Sat Jan 2 02:38:06 CET 2010


diff.zoo in the zoo package can take a vector of lags:

library(zoo)
z <- zoo(seq(10)^2)
diff(z, 1:4)

There are three vignettes (pdf documents) that come with zoo that have
more info on the package.


On Fri, Jan 1, 2010 at 8:16 PM, Rafael Moral
<rafa_moral2004 at yahoo.com.br> wrote:
> Dear useRs,
>
> I want to write a function that generates all the possible combinations of diff().
>
> Example:
> If my vector has length 5, I need the diff() until lag=4 ->
> c(diff(my.vec), diff(my.vec, lag=2), diff(my.vec, lag=3), diff(my.vec, lag=4))
>
> If it has length 4, I need until lag=3 ->
> c(diff(my.vec), diff(my.vec, lag=2), diff(my.vec, lag=3))
>
> So, it must be until lag=(length(my.vec)-1).
>
> The function I've written is:
> dif <- function(my.vec) {
> for(i in 2:(length(my.vec)-1)) {
> x.dif <- c(diff(my.vec), diff(my.vec, lag=i))
> }
> return(x.dif)
> }
>
> But it only returns the first diff() (lag=1) and the last one ( diff(my.vec, lag=(length(my.vec)-1)   )
> Example:
>> my.vec = c(1,2,3,2)
>> dif(my.vec)
> [1]  1  1 -1  1
> What I wanted to get was:
>> c(diff(my.vec), diff(my.vec, lag=2), diff(my.vec, lag=3))
> [1]  1  1 -1  2  0  1
>
> Is there a way of computing it so R understands what I want?
>
> Thanks in advance, happy new year for everyone!
>
> Kind regards,
> Rafael.
>
>
>      ____________________________________________________________________________________
> [[elided Yahoo spam]]
>
>        [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>



More information about the R-help mailing list