【问题标题】:Aggregate data frame on 2 columns, counting the leftover column by occurrence在 2 列上聚合数据框,按出现次数计算剩余列
【发布时间】:2016-05-24 11:02:27
【问题描述】:

我有一个数据框:

    station  person_id   date
1    0037     103103  2015-02-02
2    0037     306558  2015-02-02
3    0037     306558  2015-02-04
4    0037     306558  2015-02-05

我需要按电台和日期聚合帧,以便结果中的每个唯一电台/日期(每一行)显示有多少人落在该行上。

例如,前 2 行将折叠成一行,显示 0037 站和日期 2015-02-02 的 2 个人。

我试过了,

result <- data_frame %>% group_by(station, week = week(date)) %>% summarise_each(funs(length), -date)

【问题讨论】:

  • summarize_each 仅在您有多个要汇总的列时才需要,例如,如果您想在车站/日期分组中获得四个不同列的平均值。

标签: r aggregate dplyr


【解决方案1】:

你可以试试:

group_by(df, station, date) %>% summarise(num_people = length(person_id))
Source: local data frame [3 x 3]
Groups: station [?]

  station       date num_people
    (int)     (fctr)      (int)
1      37 2015-02-02          2
2      37 2015-02-04          1
3      37 2015-02-05          1

【讨论】:

  • 这不就是count(df, station, date)吗?或者至少group_by(df, station, date) %&gt;% summarise(n())
  • 优秀。谢谢。
【解决方案2】:

在基础 R 中,您可以使用 aggregate:

# sample dataset
set.seed(1234)
df <- data.frame(station=sample(1:3, 50, replace=T),
                 person_id=sample(30000:35000, 50, replace=T),
                 date=sample(seq(as.Date("2015-02-05"), as.Date("2015-02-12")
                                 by="day"), 50, replace=T))

# calculate number of people per station on a particular date
aggregate(cbind("passengerCount"=person_id) ~ station + date, data=df, FUN=length)

cbind 函数不是必需的,但它可以让您提供变量名。

【讨论】:

    【解决方案3】:

    使用data.table,我们将'data.frame'转换为'data.table',按'station'、'date'分组,我们得到行数(.N)。

    library(data.table)
    setDT(df1)[, .(num_people = .N), .(station, date)]
    #   station       date num_people
    #1:      37 2015-02-02          2
    #2:      37 2015-02-04          1
    #3:      37 2015-02-05          1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 2014-04-09
      • 2019-04-24
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多