library(nycflights13)
data <- flights
flights %>% group_by(carrier)我以nycflights13数据为例,试图弄清楚如何使用group_by函数,将载波分组在一起,并将载波us过滤为>1。
发布于 2018-05-07 22:08:52
可能对group_by的运作方式存在误解。来自?group_by:
> ?group_by
Most data operations are done on groups defined by variables. group_by() takes
an existing tbl and converts it into a grouped tbl where operations are
performed "by group" [...] grouping doesn't change how the data looks [...]
It changes how it acts with the other dplyr verbs.据我所知,您正在寻找美国航空公司相同航班的计数,这些航班>1。Group_by本身可能不是最好的选择。当在组级别应用操作时,Group_by非常有用,例如查找平均延迟时间:
> flights %>% group_by(carrier) %>% na.omit(.) %>%
summarise(mean = mean(dep_delay))
# A tibble: 16 x 2
carrier mean
<chr> <dbl>
1 9E 16.4
2 AA 8.57
3 AS 5.83
....但是,group_by本身不会更改或聚合您的数据。
> flights
# A tibble: 336,776 x 20
year month day dep_time sched_dep_time dep_delay
<int> <int> <int> <int> <int> <dbl>
1 2013 1 1 517 515 2.00
2 2013 1 1 533 529 4.00
flights %>% group_by(carrier)
A tibble: 336,776 x 20 ...请注意,没有执行任何聚合,tibble包含相同数量的观察值。正如其他人在评论中所暗示的那样,您可能需要决定要聚合哪些功能,并查看其他聚合函数以提供帮助。下面是一个示例,它使用" table“函数按载波”US“的"dest”和"origin“生成频率表。请注意,未使用group_by。
> flights %>% select(dest,carrier,origin) %>% filter(carrier == "US") %>%
table(.) %>% as_tibble(.) %>% filter(n > 1)
# A tibble: 9 x 4
dest carrier origin n
<chr> <chr> <chr> <int>
1 CLT US EWR 3232
2 PHX US EWR 1172https://stackoverflow.com/questions/50214954
复制相似问题