user2246905
user2246905

Reputation: 1039

Loop over variable names, create new variable and assign values

I am trying to determine the mean of multiple vectors. Is there a more efficient alternative than using assign within a loop to calculate the means, as I do below?

a=c(1,2,3,4)
b=c(1,3,4,3,4)
c=c(3,9,4,2,7,3,7)
for (i in c("a","b","c")) {
  assign(paste(i,"mean", sep = ""), mean(get(i)))  
}

Upvotes: 1

Views: 490

Answers (1)

josliber
josliber

Reputation: 44309

Instead of creating a new variable for each vector you want to take the mean of, I would calculate and store the average of each vector together with something like:

means <- sapply(mget(c("a", "b", "c")), mean)

This returns a named vector of averages; the average of each variable can be accessed by name:

means["a"]
#   a 
# 2.5 
means["b"]
# b 
# 3 
means["c"]
# c 
# 5

Note that this will probably simplify the code you use after calculating the means. If you had var <- "a" indicating the variable you wanted to process, you can now get its mean with means[var] instead of needing to use something clunky like get(paste0(var, "mean")).

Upvotes: 3

Related Questions