I used lapply to compute aggregate products as a new column in the data set, BUT I had to get the data, compute it, and then overwrite the original data using the assignment on each iteration lapply. I was wondering if there was a more elegant way to automatically detect a new column name for an xts object
Here is an example that gives the correct result ... it should be copied to R
library(xts) x <- xts(matrix(rnorm(10*1000,0.001,0.0001),ncol=10), Sys.Date()-c(1000:1)) colnames(x) <- paste0("x.",c(1:10)) tmp <- lapply(5:20, function(y){ tmp.cum.prod <- rollapply(x,width=y,function(z){ prod(rowMeans(z[,1:10])+1)-1 },by.column=FALSE,align="right") orig.colnames <- colnames(x) x <- merge(x,tmp.cum.prod) colnames(x) <- c(orig.colnames,paste0("cum.prod.",y)) assign("x",x,envir=.GlobalEnv) }) tail(x)
But its following lines which, I think, can be improved:
orig.colnames <- colnames(x) x <- merge(x,tmp.cum.prod) colnames(x) <- c(orig.colnames,paste0("cum.prod.",y)) assign("x",x,envir=.GlobalEnv)
Any suggestions? also, if there are other lines that you think could be improved in the above (e.g. using lapply ), I always try to learn how to write more elegant code.
thanks