【问题标题】:How to group rows in data frame while counting occurrences in one column and summing values in other?如何对数据框中的行进行分组,同时计算一列中的出现次数并对另一列中的值求和?
【发布时间】:2016-11-19 18:03:37
【问题描述】:

我正在尝试修改我的数据框:

  start end duration_time
1     1   2         2.438
2     2   1         3.901
3     1   2        18.037
4     2   3        85.861
5     3   4        83.922

并创建如下内容:

  start end duration_time weight
1     1   2        20.475      2
2     2   1         3.901      1
4     2   3        85.861      1
5     3   4        83.922      1

所以重复的开始-结束组合将被删除,权重将增加,持续时间将相加

我已经有一个零件在工作,我只是无法让重量工作:

library('plyr')

df <- read.table(header = TRUE, text = "start end duration_time
1     1   2         2.438
2     2   1         3.901
3     1   2        18.037
4     2   3        85.861
5     3   4        83.922")

ddply(df, c("start","end"), summarise, weight=? ,duration_time=sum(duration_time))

【问题讨论】:

  • “体重会增加”是什么意思?那是你的计数变量吗?
  • 您需要的所有尝试都是ddply(df, .(start, end), summarise, weight=length(duration_time), duration_time=sum(duration_time))

标签: r plyr


【解决方案1】:

base R 选项是 aggregate

do.call(data.frame, aggregate(duration_time~., df1,
       FUN = function(x) c(duration_time=sum(x), weight = length(x))))

【讨论】:

  • 不错,谢谢,你觉得这样比数据表方案慢吗?
  • @ayshelina 一般来说,aggregate 会更慢,但对于较小的数据集,这将达到目的
【解决方案2】:

使用 data.table 的最简单解决方案:

library(data.table)
setDT(df)[, .(duration_time=sum(duration_time), wt = .N) , by  =c("start", "end")]

   start end duration_time wt
1:     1   2        20.475  2
2:     2   1         3.901  1
3:     2   3        85.861  1
4:     3   4        83.922  1

尝试使用 dplyr, tidyr

library(dplyr)
library(tidyr)
df1 <- df %>% unite(by_var, start,end)
df2 <- cbind(df1 %>% count(by_var), df1 %>% group_by(by_var)%>% 
    summarise( duration_time=sum(duration_time))%>%
    separate(by_var, c("start","end")))[c(3,4,5,2)]

> df2
  start end duration_time n
1     1   2        20.475 2
2     2   1         3.901 1
3     2   3        85.861 1
4     3   4        83.922 1

【讨论】:

  • 如果你要使用 dplyr,为什么不直接df %&gt;% group_by(start, end) %&gt;% summarise(weight = n(), duration_time = sum(duration_time))
  • @rawr:这就是我想要的——把它作为其他人的答案。
  • @ayshelina 是否回答了您的问题?关注stackoverflow.com/help/someone-answers
猜你喜欢
  • 2020-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
  • 2021-08-11
  • 1970-01-01
  • 2019-12-08
  • 1970-01-01
相关资源
最近更新 更多