重新排序向量中的运行计数 [英] Reorder a running count in a vector
问题描述
我想知道是否有一种不需要 for 循环的方法来做到这一点.
I'm trying to figure out if there's a way to do this that doesn't require a for loop.
我有一个按顺序增加的数据向量,但会跳过偶尔的值.例如,测试
I have a vector of data that increases sequentially, but skips occasional values. For example, test
num[1:4651] 2 2 2 2 3 3 3 3 3 3 7 7 9 9 9 9, etc.
是否有 R 函数可以将该向量转换为从 1 开始到向量末尾的固定序列?所以,
Is there an R function that will convert that vector into a fixed sequence starting at 1 through the end of the vector? So,
1 1 1 1 2 2 2 2 3 3 4 4 4 4, etc.
推荐答案
我们可以使用match
来做到这一点
We can use match
to do this
match(test, unique(test))
#[1] 1 1 1 1 2 2 2 2 2 2 3 3 4 4 4 4
<小时>
或者另一种选择是factor
as.integer(factor(test, levels = unique(test)))
#[1] 1 1 1 1 2 2 2 2 2 2 3 3 4 4 4 4
<小时>
正如@Frank 所建议的,来自 dplyr
的 dense_rank
也可能在值增加时起作用
As @Frank suggested, dense_rank
from dplyr
may also work as the values are increasing
dplyr::dense_rank(test)
#[1] 1 1 1 1 2 2 2 2 2 2 3 3 4 4 4 4
如果值不再重复,可能可以使用rleid
If the values are not repeating again, possibly rleid
can be used
data.table::rleid(test)
#[1] 1 1 1 1 2 2 2 2 2 2 3 3 4 4 4 4
或者使用 rle
inverse.rle(within.list(rle(test), values <- seq_along(values)))
#[1] 1 1 1 1 2 2 2 2 2 2 3 3 4 4 4 4
或者另一种选择是
cumsum(c(TRUE, test[-1] != test[-length(test)]))
#[1] 1 1 1 1 2 2 2 2 2 2 3 3 4 4 4 4
或者使用 dplyr
cumsum(test != lag(test, default = TRUE))
#[1] 1 1 1 1 2 2 2 2 2 2 3 3 4 4 4 4
数据
test <- c(2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 7, 7, 9, 9, 9, 9)
这篇关于重新排序向量中的运行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!