【问题标题】:Add row to dataframe with sum of within group data将行添加到具有组内数据总和的数据框
【发布时间】:2018-12-06 17:02:31
【问题描述】:

我在下面有一个示例数据框。

eg_data <- data.frame(
time = c("1", "1", "2","2"), 
type = c("long", "short","long", "short"), 
size=c(200,50, 500, 150 ))

我需要为每个时间段创建总计大小值的行。我已经查看了聚合和 by 的组合,但我无法让它正常工作。

我尝试过的一个例子:

rbind(eg_data, data.frame(time="1 + 2", type="long", size=by(eg_data$size, 
eg_data$time=="long", sum)))   

我希望最终数据框看起来像的示例:

eg_data <- data.frame(
time = c("1", "1", "2","2", "1 + 2", "1 + 2"), 
type = c("long", "short","long", "short", "long", "short"), 
size=c(200, 50, 500, 150, 700, 200))

感谢任何帮助,非常感谢基于 R 的解决方案。

【问题讨论】:

    标签: r group-by summarization


    【解决方案1】:
    eg_data <- data.frame(
      time = c("1", "1", "2","2"), 
      type = c("long", "short","long", "short"), 
      size=c(200,50, 500, 150 ))
    
    library(dplyr)
    
    eg_data %>%
      group_by(type) %>%                               # for each type
      summarise(time = paste(time, collapse = " + "),  # combine times
                size = sum(size)) %>%                  # get sum of sizes
      bind_rows(eg_data, .)                            # add everything after your original dataset (rows)
    
    #    time  type size
    # 1     1  long  200
    # 2     1 short   50
    # 3     2  long  500
    # 4     2 short  150
    # 5 1 + 2  long  700
    # 6 1 + 2 short  200
    

    【讨论】:

    • 这正是我所需要的,但它没有将两个摘要行添加到数据框中。但它确实可以满足我的需要,谢谢您的回答。
    • 您应该将此过程的输出保存为eg_data,或保存为新的数据框。您可以在开头添加eg_data = 并添加eg_data = eg_data %&gt;% ... 之类的内容。
    • 如果数据框有很多其他列在组内是常见的,如何在不手动将所有列添加到代码的情况下保留它们? (一些因素,一些字符串等)
    • @luchonacho 您可以在开头排除这些列,或者使用select 仅保留您感兴趣的列。希望这会有所帮助。
    【解决方案2】:

    AntoniosK 和 Hugo 通过 dplyr 得到了很好的答案,我还使用 [] 和 base R 找到了这个答案

    eg_data <- rbind(eg_data, data.frame(time="1 + 2", type="long", 
    size=sum(eg_data[which(eg_data[,2]=="long"),3])))
    
    eg_data <- rbind(eg_data, (data.frame(time="1 + 2", type="short", 
    size=sum(eg_data[which(eg_data[,2]=="short"),3]))))
    

    它需要两行,不那么简洁,但它将总和行添加到数据框中,并且不会更改任何其他变量数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-24
      • 2018-08-03
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多