9

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.

2
  • 1
    I doubt you have 11 "lists" (you probably have 11 vectors). If they really are 11 vectors, it would be easiest to put them in a matrix, since rollmean can operate by column. We wouldn't have to guess if you had you provided sample data. Also, rollmean is in zoo; the TTR function is runMean. Commented Oct 27, 2011 at 15:04
  • might try either mapply or dplyr Commented Mar 21, 2018 at 21:12

3 Answers 3

8

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())
Sign up to request clarification or add additional context in comments.

1 Comment

+1, was thinking of writing answer in the same lines, get the list from the environment, then lapply, then back to environment. The problem was that I did not know these useful functions mget and list2env.
3

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))

Comments

1

This can be done with ?get and ?do.call .

x1<-1:3 
x2 <- seq(3.5,5.5,1) 
for (i in 1:2) { 
sx<- (do.call("sin",list(c(get(paste('x',i,sep='',collapse='')))))) 
cat(sx) 
} 

Sloppy example, but you get the idea, I hope.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.