【发布时间】:2018-06-13 23:51:32
【问题描述】:
我需要使用 ddply 在我的数据框的多个列上应用多个函数。当我使用列名(下面示例中的 RV)时,我的拆分变量(下面的 Group 和 Round)起作用(我得到 Round 和 Group 的每个组合的平均值)。
我需要在 20 列上执行此操作,并且我正在考虑创建一个 for 循环并传递列索引。
当我使用列索引时(例如 df[[1]],它在我的数据框中是“RV”),Group 和 Round 将被忽略,并返回 Round 和 Group 的所有组合的总平均值。
我尝试在 new.df3 中传递列名,但 Round 和 Group 再次被忽略。
df <- data.frame("RV" = 1:5, "Group" = c("a","b","b","b","a"), "Round" = c("2","1","1","2","1"))
# this works and a separate mean for each combination of "Group" and "Round" is calculated
new.df <- ddply(df, c("Group", "Round"), summarise,
mean= mean(RV))
# this does not work and the grand mean is returned for all combinations of "Group" and "Round"
new.df2 <- ddply(df, c("Group", "Round"), summarise,
mean= mean(df[[1]]))
# this does not work and the grand mean is returned for all combinations of "Group" and "Round"
new.df3 <- ddply(df, c("Group", "Round"), summarise,
mean= mean(df[,colnames(df[1])]))
我尝试了“lapply”并且存在同样的问题。有什么建议为什么会发生这种情况以及我该如何解决?
【问题讨论】:
标签: r indexing grouping multiple-columns plyr