Say I have an array of number
a <- c(1,2,3,6,7,8,9,10,20)
if the开发者_StackOverflowre 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
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
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
> 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
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论