首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找所有至少有三年R数据的航班

查找所有至少有三年R数据的航班
EN

Stack Overflow用户
提问于 2020-05-14 14:38:07
回答 2查看 198关注 0票数 3

我使用的是在R中免费获得的飞行数据集。

代码语言:javascript
复制
flights <- read_csv("http://ucl.ac.uk/~uctqiax/data/flights.csv")

现在,假设我想找到所有已经连续飞行了至少三年的航班:所以在date专栏中有三年的时间可用。基本上,我只对数据的year部分感兴趣。

我正在考虑以下方法:创建一个所有平面名称的唯一列表,然后为每一架飞机获取所有日期,并查看是否连续三年。

我开始时是这样的:

代码语言:javascript
复制
NOyears = 3
planes <- unique(flights$plane) 

# at least 3 consecutive years 
for (plane in planes){
  plane = "N576AA"
  allyears <- which(flights$plane == plane)
}

但我被困在这里了。整个方法对我来说都太复杂了。有更简单/更快的方法吗?考虑到我正在处理一个非常大的数据集.

注意:我希望能够指定一年之后的数量,这就是为什么我首先包括了NOyears = 3

编辑:

我刚刚注意到了的问题。diffcumsum的使用非常有趣,这对我来说都是新的。也许在这里使用data.table也可以采用类似的方法?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-15 01:03:47

下面是另一个使用data.table的选项

代码语言:javascript
复制
#summarize into a smaller dataset; assuming that we are not counting days to check for consecutive years
yearly <- flights[, .(year=unique(year(date))), .(carrier, flight)]

#add a dummy flight to demonstrate consecutive years
yearly <- rbindlist(list(yearly, data.table(carrier="ZZ", flight="111", year=2011:2014)))

setkey(yearly, carrier, flight, year)    
yearly[, c("rl", "rw") := {
    iscons <- cumsum(c(0L, diff(year)!=1L))
    .(iscons, rowid(carrier, flight, iscons))
}]

yearly[rl %in% yearly[rw>=3L]$rl]

产出:

代码语言:javascript
复制
   carrier flight year   rl rw
1:      ZZ    111 2011 5117  1
2:      ZZ    111 2012 5117  2
3:      ZZ    111 2013 5117  3
4:      ZZ    111 2014 5117  4
票数 0
EN

Stack Overflow用户

发布于 2020-05-14 15:12:50

dplyr会在这里完成任务

代码语言:javascript
复制
library(dplyr)
library(lubridate)

flights %>%
  mutate(year = year(date)) %>%
  group_by(plane) %>%
  summarise(range = max(year) - min(year)) %>%
  filter(range >= 2)

虽然我没有看到任何符合标准的飞机!

编辑:根据mnist的评论,连续几年比较棘手,但是下面是一个连续几个月的工作示例(您提供的数据只有一年)--只是交换几年就行了!

代码语言:javascript
复制
nMonths = 6
flights %>%
  mutate(month = month(date)) %>% #Calculate month
  count(plane, month) %>% #Summarize to one row for each plane/month combo
  arrange(plane, month) %>% #Arrange by plane, month so we can look at consecutive months
  group_by(plane) %>% #Within each plane...
  mutate(consecutiveMonths = c(0, sequence(rle(diff(month))$lengths))) %>% #...calculate the number of consecutive months each row represents
  group_by(plane) %>% #Then, for each plane...
  summarise(maxConsecutiveMonths = max(consecutiveMonths)) %>% #...return the maximum number of consecutive months
  filter(maxConsecutiveMonths > nMonths) #And keep only those planes that meet criteria!
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61800120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档