zoo - R - rollapply with multiple "by" values -


i have trying find efficient way code below:

library(zoo) maprice <- function(x,n) {     mavg <- rollapply(x, n, mean)     colnames(mavg) <- "maprice"     mavg }  price.ma.1hr <- maprice(out, 12) price.ma.2hr <- maprice(out, 24) price.ma.4hr <- maprice(out, 48) price.ma.6hr <- maprice(out, 72) 

the solution came following:

maprice <- function(x,n) {     ma <- matrix( ,nrow = nrow(x), ncol = length(n))     (i in 1:length(n)) {         ma[,i]<- rollapply(x, n[i], mean)     }     ma }  n <- c(1,2,4,6,8,12)  price.ma <- maprice(price, n) 

price vector (ncol = 1)

this still provides answer looking for, looking see if there alternate maybe efficient way. appreciated.

note: looked @ question "rollapply multiple time diffrent arguments" on so. didnt understand process.

assuming input vector v gives zoo object zz ith column formed using w[i]. as.data.frame(zz) or coredata(zz) used produce data.frame or matrix respectively if needed. setnames(w, w) reduced w if column names not important.

# inputs v <- 1:100  # data w <- c(12, 24, 48, 72)  z <- zoo(v) zz <- do.call("merge", lapply(setnames(w, w), rollmeanr, x = z)) 

or if list of vectors sufficient then:

lapply(setnames(w, w), rollmean, x = v) 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -