Please make the posting reproduciblea dn self-contained.
I have added library(Hmisc) and set.seed(1) to satisfy that.
Note that wts = wts/sum(wts) is unnecessary and try this:
library(Hmisc)
set.seed(1)
x <- matrix(rnorm(200), 10, 20)
f <- function(i) {
if (i < 5) { 0 * x[1, ]
} else apply(x[1:i,], 2, wtd.var, weights = (0.5)^(i-seq(i)),
normwt = TRUE ,
na.rm = TRUE)
}
t(sapply(1:nrow(x), f))
On 7/23/07, Young Cho <young.stat at gmail.com>
wrote:> Hi,
>
> I am doing double for loops to calculate SDs with some weights and
wondering
> if I can get rid of the outer for loop as well. I made a simple examples
> which is essentially what I am doing.
>
> Thanks for your help!
>
> -Young
>
> #------------------------------------------------------
> # wtd.var is Hmisc package
> # you can replace the 3 lines inside for loop as
> # sdx[i,] = apply(x[(i-4):i,],2,var,na.rm=T)
> # -------------------------------------------------------
>
> x = matrix(rnorm(200),10,20)
> sdx = matrix(0,10,20)
> for(i in 5:nrow(x)){
> wts = ( 0.5 )^(i-c(1:i))
> wts = wts/sum(wts)
> sdx[i,] = apply(x[1:i,],2,wtd.var,weights=wts,normwt=T,
> na.rm=T)
> }
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>