我有一个数据集 df,看起来像这样,但有几百万个实例:
Date AD Runway MTOW nr.flights
2008-01-01 A 18 376 2
2008-01-01 A 18 376 2
2008-01-01 D 36 190 1
2008-01-02 D 09 150 2
2008-01-02 A 36 280 1
2008-01-02 A 36 280 1
我希望它看起来像这样:
Date AD Runway MTOW nr.flights
2008-01-01 A 18 752 4
2008-01-01 D 36 190 2
2008-01-02 D 9 150 2
2008-01-02 A 36 560 1
基本上我想将所有相同的 Date、AD 和 Runway 行组合在一起,因此删除所有重复项。同时,我希望针对特定日期、AD 和跑道汇总 MTOW 和 nr.flights。
我试过这个:
vals <- expand.grid(Date = unique(df$Date),
Runway = unique(df$Runway),
AD = unique(df$AD))
所以我可以将它与原始数据集 df 合并,但这不起作用。我也尝试了 group_by 的几种组合,但这也没有给我想要的结果。
重现:
df <- data.frame(Date=c("2008-01-01","2008-01-01","2008-01-01","2008-01-02","2008-01-02","2008-01-02"),
AD = c("A", "A", "D", "D", "A", "A"), Runway = c(18, 18, 36, 09, 36,36),
MTOW = c(376, 376, 190, 150, 280, 280), nr.flights = c(2,2,1,2,1,1))
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激!
使用 library dplyr,您可以执行以下操作:
df %>% group_by(Date, AD, Runway) %>% summarise(MTOW = sum(MTOW), nr.flights = sum(nr.flights))
Source: local data frame [4 x 5]
Groups: Date, AD [?]
Date AD Runway MTOW nr.flights
(fctr) (fctr) (dbl) (dbl) (dbl)
1 2008-01-01 A 18 752 4
2 2008-01-01 D 36 190 1
3 2008-01-02 A 36 560 2
4 2008-01-02 D 9 150 2
Run Code Online (Sandbox Code Playgroud)
我认为已经有很多这样的帖子和例子了。
| 归档时间: |
|
| 查看次数: |
4006 次 |
| 最近记录: |