R:更新给定一组索引的向量
我有一个向量(初始化为零)和该向量的一组索引。对于索引中的每个值,我想增加向量中相应的索引。所以,假设6在索引中出现两次(如下例),那么向量的第6个元素的值应该是2 例如: 更新的向量应该是R:更新给定一组索引的向量,r,vector,R,Vector,我有一个向量(初始化为零)和该向量的一组索引。对于索引中的每个值,我想增加向量中相应的索引。所以,假设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 不使用循环最惯用的方法是什么?函数tablate就是为此而设计的 > indices = c(7,8,6,6,2); > tabulate(bin=indices, nb
> c(0, 1, 0, 0, 0, 2, 1, 1, 0, 0)
[1] 0 1 0 0 0 2 1 1 0 0
不使用循环最惯用的方法是什么?函数
tablate
就是为此而设计的
> indices = c(7,8,6,6,2);
> tabulate(bin=indices, nbins=10);
[1] 0 1 0 0 0 2 1 1 0 0
功能
制表
就是为此而设计的
> 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
x您可以为此使用rle
:
x <- rle(sort(indices))
v[x$values] <- x$lengths
v
# [1] 0 1 0 0 0 2 1 1 0 0
x这太好了。谢谢那太好了。谢谢