[R] programming to calculate variance

Petr PIKAL petr.pikal at precheza.cz
Wed Sep 30 13:45:42 CEST 2009


marlene marchena <marchenamarlene at gmail.com> napsal dne 30.09.2009 
13:28:16:

> Hi Petr,
> 
> Thanks for your suggestion. It woks, but now I have other problem the 
> positions of the values changed. I need the NA values in the three first 
positions.
> 
>  y=c(2,1,5,8,11,3,1,7,50,21,33,7,60)
> x=as.zoo(y)
> > x
>  1  2  3  4  5  6  7  8  9 10 11 12 13 
>  2  1  5  8 11  3  1  7 50 21 33  7 60 
> 
> varx=rollapply(x,3,var)
> 
>              2          3                4            5                  

> 6               7              8                9                 
10         
> 11         12 
>   4.333333  12.333333   9.000000  16.333333  28.000000   9.333333 
714.333333 
> 481.000000 212.333333 169.333333 702.333333 


win<-3
varx=rollapply(x,win,var)
varx[1:win]<-NA

Regards
Petr





> 
> 

> 2009/9/30 Petr PIKAL <petr.pikal at precheza.cz>
> Hi
> 
> Try
> 
> function rollapply from zoo.It can compute rolling results of functions.
> Make your y a zoo object and use rollapply(object, 3, var)
> 
> Regards
> Petr
> 
> r-help-bounces at r-project.org napsal dne 30.09.2009 12:37:36:
> 
> > Dear R-user
> >
> > Suppose I have the following data
> >
> >  y=c(2,1,5,8,11,3,1,7,50,21,33,7,60)
> >
> > x=data.frame(y)
> >
> > for(i in 4:nrow(x)) x[i,] =var(x[i-3:i-1,])
> >
> > I'm trying to get a new variable with the variance of the 3 previous
> values
> > (just an example) and with NA in the three first positions. I know 
that
> my
> > for() is wrong
> > but I'm not able to find my error.
> >
> > Any idea?
> >
> > Thanks,
> >
> > Marlene.
> >
> >    [[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