# 类似于rle的函数捕获相邻整数的“运行”rle-like function that catches “run” of adjacent integers

``````x <- c(3:5, 10:15, 17, 22, 23, 35:40)
``````

``````lengths: 3, 6, 1, 2, 6
values: (3,4,5), (10,11,12... # you get the point
``````

## 4 个回复4

### ===============>>#1 票数：8 已采纳

1）根据值计算值然后计算长度

``````s <- split(x, cumsum(c(0, diff(x) != 1)))
run.info <- list(lengths = unname(sapply(s, length)), values = unname(s))
``````

``````> str(run.info)
List of 2
\$ lengths: int [1:5] 3 6 1 2 6
\$ values :List of 5
..\$ : num [1:3] 3 4 5
..\$ : num [1:6] 10 11 12 13 14 15
..\$ : num 17
..\$ : num [1:2] 22 23
..\$ : num [1:6] 35 36 37 38 39 40
``````

2）根据长度计算长度，然后计算值

``````lens <- rle(x - seq_along(x))\$lengths
list(lengths = lens, values = unname(split(x, rep(seq_along(lens), lens))))
``````

3）计算长度和值而不使用其他

``````list(lengths = rle(x - seq_along(x))\$lengths,
values = unname(split(x, cumsum(c(0, diff(x) != 1)))))
``````

### ===============>>#2 票数：6

``````rle(x - 1:length(x))\$lengths
# 3 6 1 2 6
``````

### ===============>>#3 票数：5

``````rle_consec <- function(x)
{
if (!is.vector(x) && !is.list(x))
stop("'x' must be an atomic vector")
n <- length(x)
if (n == 0L)
return(structure(list(lengths = integer(), values = x),
class = "rle_consec"))
y <- x[-1L] != x[-n] + 1
i <- c(which(y | is.na(y)), n)
structure(list(lengths = diff(c(0L, i)), values = x[i]),
class = "rle_consec")
}
``````

``````> x <- c(3:5, 10:15, 17, 22, 23, 35:40)
> rle_consec(x)
\$lengths
[1] 3 6 1 2 6

\$values
[1]  5 15 17 23 40

attr(,"class")
[1] "rle_consec"
``````

5回复

2回复

1回复

1回复

1回复

1回复

1回复

2回复

2回复

3回复