R:更新给定一组索引的向量



i有一个向量(初始化为零)和该向量的一组索引。对于索引中的每个值,我想增加向量中的相应索引。因此,假设6在索引中发生两次(如下示例),则向量的6个元素的值应为2。

eg:

> v = rep(0, 10)
> v
 [1] 0 0 0 0 0 0 0 0 0 0
> indices
 [1] 7 8 6 6 2

更新的向量应为

> c(0, 1, 0, 0, 0, 2, 1, 1, 0, 0)
 [1] 0 1 0 0 0 2 1 1 0 0

在不使用循环的情况下,最惯用的方法是什么?

为该功能tabulate是为

制作的
> indices = c(7,8,6,6,2);
> tabulate(bin=indices, nbins=10);
 [1] 0 1 0 0 0 2 1 1 0 0

您可以使用rle

x <- rle(sort(indices))
v[x$values] <- x$lengths
v
#  [1] 0 1 0 0 0 2 1 1 0 0

最新更新