我使用的是在R中免费获得的飞行数据集。
flights <- read_csv("http://ucl.ac.uk/~uctqiax/data/flights.csv")现在,假设我想找到所有已经连续飞行了至少三年的航班:所以在date专栏中有三年的时间可用。基本上,我只对数据的year部分感兴趣。
我正在考虑以下方法:创建一个所有平面名称的唯一列表,然后为每一架飞机获取所有日期,并查看是否连续三年。
我开始时是这样的:
NOyears = 3
planes <- unique(flights$plane)
# at least 3 consecutive years
for (plane in planes){
plane = "N576AA"
allyears <- which(flights$plane == plane)
}但我被困在这里了。整个方法对我来说都太复杂了。有更简单/更快的方法吗?考虑到我正在处理一个非常大的数据集.
注意:我希望能够指定一年之后的数量,这就是为什么我首先包括了NOyears = 3。
编辑:
我刚刚注意到了这的问题。diff和cumsum的使用非常有趣,这对我来说都是新的。也许在这里使用data.table也可以采用类似的方法?
发布于 2020-05-15 01:03:47
下面是另一个使用data.table的选项
#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]产出:
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发布于 2020-05-14 15:12:50
dplyr会在这里完成任务
library(dplyr)
library(lubridate)
flights %>%
mutate(year = year(date)) %>%
group_by(plane) %>%
summarise(range = max(year) - min(year)) %>%
filter(range >= 2)虽然我没有看到任何符合标准的飞机!
编辑:根据mnist的评论,连续几年比较棘手,但是下面是一个连续几个月的工作示例(您提供的数据只有一年)--只是交换几年就行了!
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!https://stackoverflow.com/questions/61800120
复制相似问题