views:

67

answers:

3

Say I have an array of number

a <- c(1,2,3,6,7,8,9,10,20)

if there a way to tell R to output just the range of the continuous sequence from "a" e.g., the continuous sequences in "a" are the following

1,3 6,10 20

Thanks a lot! Derek

+2  A: 

I don't think there is a straight way, but you could create two logical vectors telling you if next/previous element is 1 greatest/least. E.g.:

data.frame(
  a,
  is_first = c(TRUE,diff(a)!=1),
  is_last = c(diff(a)!=1,TRUE)
)
# Gives you:
   a is_first is_last
1  1     TRUE   FALSE
2  2    FALSE   FALSE
3  3    FALSE    TRUE
4  6     TRUE   FALSE
5  7    FALSE   FALSE
6  8    FALSE   FALSE
7  9    FALSE   FALSE
8 10    FALSE    TRUE
9 20     TRUE    TRUE

So ranges are:

cbind(a[c(TRUE,diff(a)!=1)], a[c(diff(a)!=1,TRUE)])
[1,]    1    3
[2,]    6   10
[3,]   20   20
Marek
+1  A: 

I did this (not so elegant I admit) in case you want all the numbers of each sequence in a list

a <- c(1,2,3,6,7,8,9,10,20)

z <- c(1,which(c(1,diff(a))!=1))

g <- lapply(seq(1:length(z)),function(i) {
if (i < length(z)) a[z[i] : (z[i+1] - 1)] 
else a[z[i] : length(a)] 
})


[[1]]
[1] 1 2 3

[[2]]
[1]  6  7  8  9 10

[[3]]
[1] 20

Then you can get a 2D array with something like this

sapply(g,function(x) c(x[1],x[length(x)]))

     [,1] [,2] [,3]
[1,]    1    6   20
[2,]    3   10   20
gd047
A: 
> a <- c(1,2,3,6,7,8,9,10,20)
> N<-length(a)
> k<-2:(N-1)
> z<-(a[k-1]+1)!=a[k] | (a[k+1]-1)!=a[k]
> c(a[1],a[k][z],a[N])
[1]  1  3  6 10 20
Jyotirmoy Bhattacharya