Reputation: 848
Using R, I want to efficiently identify which values in a sequence are missing. I've written the below example of how I do it. There must be a better way. Can someone help?
data.list=c(1,2,4,5,7,8,9)
full.list=seq(from = 1, to = 10, by =1)
output <- c()
for(i in 1:length(full.list)){
holder1 <- as.numeric(any(data.list == i))
output[i] <- holder1
}
which(output == 0)
Upvotes: 7
Views: 4460
Reputation: 919
Using grep()
:
grep(paste("^", data.list, "$", sep = "", collapse = "|"), full.list, invert = TRUE)
You could be "lazy" and use collapse = ^|$
but use the above for precise accuracy.
Using grepl()
:
full.list[!grepl(paste("^", data.list, "$", sep = "", collapse = "|"), full.list)]
Upvotes: 0
Reputation: 121578
Another option using match
(similar to %in%
)
full.list[!match(full.list,data.list,nomatch=FALSE)]
[1] 3 6 10
Upvotes: 2