lundi 22 juin 2015

R: recursive function to give groups of consecutive numbers

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.

Aucun commentaire:

Enregistrer un commentaire