Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Create variables in loop

Tags:

r

I have 11 lists of different length, imported into R as p1,p2,p3,...,p11. Now I want to get the rollmean (library TTR) from all lists and name the result p1y,p2y,...,p11y.

This seems to be the job for a loop, but I read that this is often not good practice in R. I tried something (foolish) like

sample=10
for (i in 1:11){
paste("p",i,"y",sep="")<-rollmean(paste("p",i,sep=""),sample)
}

which does not work. I also tried to use it in combination with assign(), but as I understand assign can only take a variable and a single value.

As always it strikes me that I am missing some fundamental function of R.

like image 967
Martin H Avatar asked Feb 03 '23 12:02

Martin H


2 Answers

As Manuel pointed out, your life will be easier if you combine the variables into a list. For this, you want mget (short for "multiple get").

var_names <- paste("p", 1:11, sep = "")
p_all <- mget(var_names, envir = globalenv())

Now simply use lapply to call rollmean on each element of your list.

sample <- 10
rolling_means <- lapply(p_all, rollmean, sample)

(Also, consider renaming the sample to something that isn't already a function name.)

I suggest leaving the answers as a list, but if you really like the idea of having separate rolling mean variables to match the separate p1, p11 variables then use list2env.

names(rolling_means) <- paste(var_names, "y", sep = "")
list2env(rolling_means, envir = globalenv())
like image 128
Richie Cotton Avatar answered Feb 05 '23 12:02

Richie Cotton


You could group your lists into one and do the following

sample <- 10
mylist <- list(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11)
for(i in 1:11) assign(paste('p',i,'y',sep=''), rollmean(mylist[i], sample))
like image 29
Manuel Ramón Avatar answered Feb 05 '23 14:02

Manuel Ramón