Standard Deviation Loop in R -
i want create loop takes standard deviation of positions 1 through 3 in "y" takes standard deviation of positions 4 through 6 etc.
here code came far stuck since new vector "i" increasing same values.
here hypothetical dataset.
x <-rep(1:10, each =3) y <- rnorm(30, mean=4,sd=1) data <- cbind(x,y) sd.v = null (i in c(1,4,7,10)){ sd.v[i] <- sd(y[c(i,i+1,i+2)]) }
i more interested in creating loop rather using apply
, sapply
, tapply
or else.
if want loop, here approach:
set.seed(42) y <- rnorm(30, mean=4,sd=1) sd.y <- as.numeric() for(i in 1:10){ sd.y[i] <- sd(y[(1+(i-1)*3):(3+(i-1)*3)]) } sd.y # [1] 0.9681038 0.3783425 1.1031686 1.1799477 0.6867556 1.6987277 # [7] 1.8859794 1.4993717 1.2956209 1.1116502