我有一个数据框,其中许多变量是矩阵,它们为自己的列共享相似的列名。我想将函数应用于所有变量的特定列。
以下代码是数据示例,并尝试这样做。但是,尝试使用paste()
函数生成的名称访问列时出现错误。
data_all <- data.frame(time=sample(seq(1, 20), 1000, replace=TRUE), A= runif(1000), B= runif(1000))
str(data_all)
data_all_agg <- data.frame(aggregate(list(A = data_all[, 'A']), list(time = data_all[, 'time']), function (x) quantile(x, probs = c(0.2, 0.5, 0.8)) ))
data_all_agg <- cbind(data_all_agg, data.frame(aggregate(list(B = data_all[, 'B']), list(time = data_all[, 'time']), function (x) quantile(x, probs = c(0.2, 0.5, 0.8)) )))
data_all_agg <- data_all_agg[!duplicated(lapply(data_all_agg, summary))]
#
var_names <- c("A", "B")
for (var_name_counter in c(1:2)) {
get(paste("data_all_agg$", var_names[var_name_counter],"[,\"50%\"]", sep=""))
}
Error in get(paste("data_all_agg$", var_names[var_name_counter], "[,\"50%\"]", :
object 'data_all_agg$A[,"50%"]' not found
而如果我直接输入data_all_agg$A[,"50%"]
,我会得到以下值:
> data_all_agg$A[,"50%"]
[1] 0.4620452 0.4874819 0.5084974 0.5524401 0.5282378 0.4586645 0.5726048
[8] 0.5040240 0.5196544 0.6153615 0.5439682 0.5331080 0.5607132 0.4661196
[15] 0.5572938 0.6014468 0.5490722 0.5181902 0.4968988 0.5233519
此外,使用eval()
,它给出的字符串不是值:
for (var_name_counter in c(1:2)) {
Res <- eval(paste("data_all_agg$", var_names[var_name_counter],"[,\"50%\"]", sep=""))
}
> Res
[1] "data_all_agg$B[,\"50%\"]"
任何想法?