gpt4 book ai didi

r - 如何在基础 R 中分组

转载 作者:行者123 更新时间:2023-12-04 23:13:20 24 4
gpt4 key购买 nike

我想使用 基 R (没有任何特定包)表达以下 SQL 查询:

select month, day, count(*) as count, avg(dep_delay) as avg_delay
from flights
group by month, day
having count > 1000

它选择平均起飞延误和繁忙天(航类数超过 1000 天)每天的航类数。数据集 nycflights13 包含 2013 年从纽约出发的航类信息。

请注意,我可以在 dplyr 中轻松地将其编写为:
flights %>%
group_by(month, day) %>%
summarise(count = n(), avg_delay = mean(dep_delay, na.rm = TRUE)) %>%
filter(count > 1000)

最佳答案

由于我之前被提醒过 by 的优雅(@Parfait 的提示),这里是一个使用 by 的解决方案:

res <- by(flights, list(flights$month, flights$day), function(x)
if (nrow(x) > 1000) {
c(
month = unique(x$month),
day = unique(x$day),
count = nrow(x),
avg_delay = mean(x$dep_delay, na.rm = TRUE))
})

# Store in data.frame and order by month, day
df <- do.call(rbind, res);
df <- df[order(df[, 1], df[, 2]) ,];
# month day count avg_delay
#[1,] 7 8 1004 37.296646
#[2,] 7 9 1001 30.711499
#[3,] 7 10 1004 52.860702
#[4,] 7 11 1006 23.609392
#[5,] 7 12 1002 25.096154
#[6,] 7 17 1001 13.670707
#[7,] 7 18 1003 20.626789
#[8,] 7 25 1003 19.674134
#[9,] 7 31 1001 6.280843
#[10,] 8 7 1001 8.680402
#[11,] 8 8 1001 43.349947
#[12,] 8 12 1001 8.308157
#[13,] 11 27 1014 16.697651
#[14,] 12 2 1004 9.021978

关于r - 如何在基础 R 中分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49669862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com