1

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)))  
}
1
  • 1
    try list2env('names<-'(lapply(list(a,b,c), mean), paste0(c('a', 'b', 'c'),'mean')),.GlobalEnv) Although you should learn to work with lists to avoid this syntax Commented Sep 2, 2015 at 18:53

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.