在大型数据集R上按id检查序列
我需要检查大数据集中的年份值是否连续。
这是数据的样子:
b <- c(2011,2012,2010, 2009:2011, 2013,2015,2017, 2010,2010, 2011)
dat <- data.frame(cbind(a,b))
dat
a b
1 1 2011
2 1 2012
3 1 2010
4 2 2009
5 2 2010
6 2 2011
7 3 2013
8 3 2015
9 3 2017
10 4 2010
11 4 2010
12 5 2011
这是我写的函数。它在小数据集上效果很好。然而,真实的数据集非常大,有 20 万个 id,而且需要很长时间。我该怎么做才能让它更快?
seqyears <- function(id, year, idlist) {
year <- as.numeric(year)
year_values <- year[id==idlist]
year_sorted <- year_values[order(year_values)]
year_diff <- diff(year_sorted)
answer <- unique(year_diff)
if(length(answer)==0) {return("single line")} else { # length 0 means that there is only value and hence no diff can be computed
if(length(answer)==1 & answer==1) {return("sequence ok")} else {
return("check sequence")}}
}
得到一个值向量
unlist(lapply(c(1:5), FUN=seqyears, id=dat$a, year=dat$b))
回答
我认为你可以更简单地汇总它。
aggregate(dat$b, dat[,"a",drop=FALSE], function(z) any(diff(sort(z)) != 1))
# a x
# 1 1 FALSE
# 2 2 FALSE
# 3 3 TRUE
# 4 4 TRUE
# 5 5 FALSE
如果你需要它是那个字符串, anifelse做你需要的:
aggregate(dat$b, dat[,"a",drop=FALSE],
function(z) ifelse(any(diff(sort(z)) != 1), "check sequence", "sequence ok"))
# a x
# 1 1 sequence ok
# 2 2 sequence ok
# 3 3 check sequence
# 4 4 check sequence
# 5 5 sequence ok
如果您有机会重复多年(这是可以接受的),那么您可以将内部匿名函数从 更改diff(sort(z))为diff(sort(unique(z)))。