Reputation: 3768
Given a sorted vector x
:
x <- c(1,2,4,6,7,10,11,12,15)
I am trying to write a small function that will yield a similar sized vector y
giving the last consecutive integer in order to group consecutive numbers. In my case it is (defining groups 2, 4, 7, 12 and 15):
> y
[1] 2 2 4 7 7 12 12 12 15
I tried this this recursive idea (were x is the vector, and i an index that would start by 1 in most cases: if the content of the next index is one larger than the current i, then call the function with i+1; else return the content):
fun <- function(x,i){
ifelse(x[i]+1 == x[i+1],
fun(x,i+1),
return(x[i]))
}
However:
> sapply(x,fun,1)
[1] NA NA NA NA NA NA NA NA NA
How to get this to work.
Upvotes: 0
Views: 228
Reputation: 23798
Maybe this helps:
find_non_consec <- function(x){ c(x[which(as.logical(diff(x)-1))],x[length(x)]) }
x <- c(1,2,4,6,7,10,11,12,15)
res <- find_non_consec(x)
The result is:
> res
[1] 2 4 7 12 15
This function identifies the numbers where the series ceases to be consecutive.
Upvotes: 2
Reputation: 7806
Your sapply call is applying fun
across all values of x
, when you really want it to be applying across all values of i
. To get the sapply to do what I assume you want to do, you can do the following:
sapply(X = 1:length(x), FUN = fun, x = x)
[1] 2 2 4 7 7 12 12 12 NA
Although it returns NA as the last value instead of 15. This is because I don't think your function is set up to handle the last value of a vector (there is no x[10], so it returns NA). You can probably edit your function to handle this fairly easily.
Upvotes: 3