【问题标题】:adding row/column total data when aggregating data using plyr and reshape2 package in R在 R 中使用 plyr 和 reshape2 包聚合数据时添加行/列总数据
【发布时间】:2014-01-09 02:18:19
【问题描述】:

我在工作期间的大部分时间都使用以下流程创建汇总表:

set.seed(1)
temp.df <- data.frame(var1=sample(letters[1:5],100,replace=TRUE),
                      var2=sample(11:15,100,replace=TRUE))
temp.output <- ddply(temp.df,
                     c("var1","var2"),
                     function(df) {
                       data.frame(count=nrow(df))
                     })
temp.output.all <- ddply(temp.df,
                         c("var2"),
                         function(df) {
                           data.frame(var1="all",
                                      count=nrow(df))
                         })

temp.output <- rbind(temp.output,temp.output.all)
temp.output[,"var1"] <- factor(temp.output[,"var1"],levels=c(letters[1:5],"all"))
temp.output <- dcast(temp.output,formula=var2~var1,value.var="count",fill=0)

当我创建一个新的聚合表时,每次编写“样板”代码以包含行/列总计时,我开始觉得很愚蠢,有什么方法可以跳过它吗?

【问题讨论】:

    标签: r plyr reshape2


    【解决方案1】:

    看看你想要的输出(现在我在电脑前),也许你应该看看dcastmargins参数:

    library(reshape2)
    dcast(temp.df, var2 ~ var1, value.var = "var2", 
          fun.aggregate=length, margins = "var1")
    #   var2 a b c d e (all)
    # 1   11 3 1 6 4 2    16
    # 2   12 1 3 6 5 5    20
    # 3   13 5 9 3 6 1    24
    # 4   14 4 7 3 6 2    22
    # 5   15 0 5 1 5 7    18
    

    还要查看基础 R 中的 addmargins 函数。

    【讨论】:

      猜你喜欢
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多