[R] sequences extraction
Julien Barnier
jbarnier at ens-lsh.fr
Fri Apr 20 11:14:21 CEST 2007
Hi,
> I need to extract sequences from an ordered vector.
> For example, if
> a<-c(1,2,3,6,10,11,13)
> I need to get the followings 4 vectors
> (1,2,3),(6),(10,11),(13)
There should be a more elegant way to do it, but the following code
seems to work (it returns the results a s a list) :
a<-c(9,1,2,3,6,10,11,17,13,14)
d <- diff(a)
result <- list()
tmp <- a[1]
for (i in 1:length(d)) {
if (d[i]==1) {
tmp <- c(tmp, a[i+1])
} else {
result <- c(result,list(tmp))
tmp <- a[i+1]
}
}
result <- c(result,list(tmp))
result
Hope that helps,
Julien
--
Julien Barnier
Groupe de recherche sur la socialisation
ENS-LSH - Lyon, France
More information about the R-help
mailing list