假设我有一个值向量,例如:
A C A B A C C B B C C A A A B B B B C A
我想为每个元素创建一个新向量,其中包含自上次出现该元素以来的元素数量。因此,对于上述向量,NA NA 2 NA 2 4 1 4 1 3 1 7 1 1 6 1 1 1 8 6
(其中NA
表示这是第一次看到该元素)。例如,第一和第二A分别位于位置1和3,相差2;第三和第四个A在位置4和11,相差7,依此类推。
有一个预先建立的管道兼容功能可以做到这一点吗?
我一起破解了这个功能来演示:
# For reproducibility
set.seed(1)
# Example vector
x = sample(LETTERS[1:3], size = 20, replace = TRUE)
compute_lag_counts = function(x, first_time = NA){
# return vector to fill
lag_counts = rep(-1, length(x))
# values to match
vals = unique(x)
# find all positions of all elements in the target vector
match_list = grr::matches(vals, x, list = TRUE)
# compute the lags, then put them in the appropriate place in the return vector
for(i in seq_along(match_list))
lag_counts[x == vals[i]] = c(first_time, diff(sort(match_list[[i]])))
# return vector
return(lag_counts)
}
compute_lag_counts(x)
尽管它似乎可以完成预期的工作,但我还是想使用别人提供的高效,久经考验的解决方案!我的搜索已空了,鉴于这似乎是一项常见的任务,这令我感到惊讶。
最佳答案
或者
ave(seq.int(x), x, FUN = function(x) c(NA, diff(x)))
# [1] NA NA 2 NA 2 4 1 4 1 3 1 7 1 1 6 1 1 1 8 6
我们为每组diff
计算索引的第一个x
差。@Henrik带来的
data.table
选项library(data.table)
dt = data.table(x)
dt[ , d := .I - shift(.I), x]
dt
关于r - 向量中不同元素之间的元素数计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62763723/