I need to check if values for year are consecutive in a large data set.
This is how the data look:
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
This is the function I wrote. It works very well on the small data set. However the real data set is very large 200k ids and it is taking a very long time. What can I do to make it faster?
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")}}
}
to get a vector of values
unlist(lapply(c(1:5), FUN=seqyears, id=dat$a, year=dat$b))