[英]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? 有没有比在循环中使用
assign
更有效的替代方案来计算均值,如下所示?
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)))
}
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"))
. 如果你有
var <- "a"
表示你想要处理的变量,你现在可以用means[var]
得到它的平均值,而不需要使用像get(paste0(var, "mean"))
一样笨重的东西get(paste0(var, "mean"))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.