如果我有像这样的向量
"a": 0 0 1 1 1 0 0 0 0 1 1 0 0 0
如何生成包含连续元素数的相同长度的向量,如下所示:
"b": 2 2 3 3 3 4 4 4 4 2 2 3 3 3
我尝试过rle,但是我没有设法以这种方式进行扩展。
答案 0 :(得分:9)
另一个使用rle
和rep
的选项
with(rle(a), rep(lengths, times = lengths))
# [1] 2 2 3 3 3 4 4 4 4 2 2 3 3 3
数据
a <- c(0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0)
答案 1 :(得分:5)
使用diff
创建分组变量,并在ave
中使用它来计算每个组的length
。
ave(x, cumsum(c(0, diff(x) != 0)), FUN = length)
# [1] 2 2 3 3 3 4 4 4 4 2 2 3 3 3
您可以对dplyr
lag
library(dplyr)
ave(x,cumsum(x != lag(x, default = FALSE)), FUN = length)
#[1] 2 2 3 3 3 4 4 4 4 2 2 3 3 3
为了完整起见,data.table
rleid
library(data.table)
ave(x, rleid(x), FUN = length)
#[1] 2 2 3 3 3 4 4 4 4 2 2 3 3 3
数据
x <- c(0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0)
答案 2 :(得分:1)
这是使用vapply
count_consec <- function (a) {
# creating output vector out
out <- integer(length(a))
# consecutive differences
diffs <- which(diff(a) != 0)
# returning 0 just in order to have a return statement in vapply - you can return anything else
vapply(1:(length(diffs)+1), function (k) {
if (k == 1) {
out[1:diffs[1]] <<- diffs[1]
return (0L)
}
if (k == length(diffs)+1) {
out[(diffs[k-1]+1):length(out)] <<- length(out) - diffs[k-1]
return (0L)
}
out[(diffs[k-1]+1):diffs[k]] <<- diffs[k] - diffs[k-1]
return (0L)
}, integer(1))
out
}
count_consec(a)
# [1] 2 2 3 3 3 4 4 4 4 2 2 3 3 3
带有数据a <- as.integer(unlist(strsplit('0 0 1 1 1 0 0 0 0 1 1 0 0 0', ' ')))