简体   繁体   English

在 R 中提取唯一列组合并查找总和和计数

[英]Extracting unique column combination and finding sum and count in R

I have a flight database with 4 columns like shown below.我有一个包含 4 列的航班数据库,如下所示。

Original:原来的:

I want an output which gives rows based on unique combination of 3 col (origin/destination/Airline), sums the number of passengers for each unique combination and count the numbers of rows for each unique combination.我想要一个 output,它根据 3 col(出发地/目的地/航空公司)的唯一组合给出行,将每个唯一组合的乘客数量相加,并计算每个唯一组合的行数。 The result would be something like this.结果将是这样的。

Output: Output:

I am able to do 1 part of it using the group_by function我可以使用group_by function 完成其中的一部分

df %>% group_by(Origin, destination, carrier) %>% summarise(count = n())

How to include the sum of population?如何包括人口总和?

We can use dplyr我们可以使用dplyr

library(dplyr)
df1 %>%
   group_by(Origin, Destination, Airline) %>%
   dplyr::summarise(count = n(), TotalPassengers = sum(Passengers))
# Groups:   Origin, Destination [2]
#  Origin Destination Airline count TotalPassengers
#  <chr>  <chr>       <chr>   <int>           <dbl>
#1 ABE    ATL         9A          2               3
#2 ABE    ATL         DL          1               5
#3 NYC    SFA         AA          3              21
#4 NYC    SFA         DL          1               5

data数据

df1 <- data.frame(Origin = rep(c("ABE", "NYC"), c(3, 4)),
      Destination = rep(c("ATL", "SFA"), c(3, 4)),
      Airline = c("9A", "9A", "DL", "AA", "AA", "AA", "DL"),
      Passengers = c(2, 1, 5, 4, 10, 7, 5))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM