【问题标题】:How to calculate the number of flights with an specific condition如何计算特定条件的航班数量
【发布时间】:2020-07-27 20:14:34
【问题描述】:

我正在使用 nycflights13::flights 数据框,想计算一架飞机在第一次延误超过 1 小时之前飞行的航班数量。我怎样才能做到这一点?我尝试过使用 group_by 和过滤器,但我做不到。有没有一种方法可以计算行数直到一个条件(例如直到第一个 dep_delay >60)?

谢谢。

【问题讨论】:

  • 请显示您尝试过的代码。虽然我们可能只能给您答案,但了解您尝试的“为什么”没有正常工作可能会提供更多信息。
  • OFAJ,欢迎来到 SO!请阅读如何产生“可重现”的问题。这包括您尝试过的示例代码(包括列出非基础 R 包以及收到的任何错误/警告)、示例明确数据(例如,dput(head(x))data.frame(x=...,y=...))和预期输出.参考:stackoverflow.com/q/5963269minimal reproducible examplestackoverflow.com/tags/r/info。 (向我们展示您迄今为止尝试过的代码也表明您已经付出了努力。由于 SO 不是一个教程/howto 网站,因此希望您在来这里之前做一些研究/努力。)
  • 好的,谢谢。你说得对,我下次再做。

标签: r


【解决方案1】:
library(dplyr)
library(nycflights13)
data("flights")

可能有更优雅的方式,但此代码计算每架飞机的航班总数(忽略已取消的航班)并将其与未取消的航班相结合,按唯一的飞机标识符 (tailnum) 分组,按出发日期/时间排序,分配 row_number 减 1,过滤延迟>60,并取第一行。

select(
  filter(flights, !is.na(dep_time)) %>% 
  count(tailnum, name="flights") %>% left_join(
      filter(flights, !is.na(dep_time)) %>% 
      group_by(tailnum) %>%
      arrange(month, day, dep_time) %>%
      mutate(not_delayed=row_number() -1) %>%
      filter(dep_delay>60) %>% slice(1)), 
  tailnum, flights, not_delayed)

# A tibble: 4,037 x 3
   tailnum flights not_delayed
   <chr>     <int>       <dbl>
 1 D942DN        4           0
 2 N0EGMQ      354          53
 3 N10156      146           9
 4 N102UW       48          25
 5 N103US       46          NA
 6 N104UW       47           3
 7 N10575      272           0
 8 N105UW       45          22
 9 N107US       41          20
10 N108UW       60          36
# ... with 4,027 more rows

这架尾号为 N103US 的飞机已经完成了 46 次飞行,其中没有一个航班延误超过 1 小时。因此,它第一个延误 1 小时之前完成的航班数量是未定义的或 NA。

【讨论】:

  • 感谢您的回答。当我正在寻找一架飞机在延误超过一小时之前的航班数量时,我根据你的尝试了这个脚本:flights %>% filter(!is.na(dep_time)) %>% #select(carrier , 月, 日, dep_time, dep_delay) %>% group_by(tailnum) %>% 排列(month, day, dep_time) %>% mutate(First_delay = row_number()) %>% filter(dep_delay % summarise(n()) 不幸的是,它给了我延误少于一小时的航班数量。
  • OFAJ,“不到一小时的延迟”,可能是因为您使用了&lt;=60 而不是&gt;60
【解决方案2】:

我得到了答案:

flights %>%
#Eliminate the NAs
filter(!is.na(dep_time)) %>% 
#Sort by date and time
arrange(time_hour) %>% 
group_by(tailnum) %>%
#cumulative number of flights delayed more than one hour
mutate(acum_delay = cumsum(dep_delay > 60)) %>% 
#count the number of flights                                         
summarise(before_1hdelay = sum(acum_delay < 1))

【讨论】:

  • 漂亮优雅。除了三架飞机外,我修改后的答案与您的答案相同。不同之处在于我按月+日+dep_time 排序,而你按time_hour 排序。例如,1 月 13 日的 N322NB 安排了两个航班。原定早上8点出发的,居然是下午6点出发的!但在上午 11 点,原定于上午 11 点 14 分起飞的同一架飞机实际上准时起飞,因此应将其包含在您的答案中,即 6 个航班,而不是 5 个。
  • 感谢您的回答,很好的解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-08
  • 2021-11-03
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 2023-03-23
相关资源
最近更新 更多