【问题标题】:R ddply ignores split factors when column index is used使用列索引时,R ddply 忽略拆分因子
【发布时间】: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


    【解决方案1】:

    plyr 一样出色的软件包,您最好在这里更新到它的最新版本dplyr。在那里,代码将是

    v <- vars(RV) # add all your variables here
    new.df <- df %>%
      group_by(Group, Round) %>%
      summarize_at(v, funs(mean))
    

    因此,使用这种方法,您将所有变量插入v,您将得到所有变量的平均值,对于GroupRound 的每个组合。管道运算符 (%&gt;%) 在您第一次看到时看起来很奇怪,但它有助于简化您的代码。它获取前一个函数的输出并将其设置为下一个函数的第一个参数。很容易看出我们采用df,按GroupRound 分组,然后对它们进行汇总。

    如果您真的想坚持使用plyr,我们也可以在那里找到解决方案:

    new.df <- ddply(df, c("Group", "Round"), summarise,
      RV_mean = mean(RV),
      var2_mean = mean(var2) # add a more variables just like this
    )
    

    我们也可以使用您的列表方法:

    new.df2 <- ddply(df, .(Group, Round), function(data_subset) { # note alternative way to reference Group and Round
      as.data.frame(llply(data_subset[,c("RV"), drop = FALSE], mean)) # add your variables here
    })
    

    请注意,在ddply 中,我总是在我的函数调用中引用数据框的子集,我从不引用dfdf 总是指原始数据框,而不是您尝试使用的子集。

    【讨论】:

    • 感谢 Melissa,您的第一个 dplyr 建议效果很好。
    猜你喜欢
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多