R :给定一组索引更新向量 [英] R : Updating a vector given a set of indices

查看:23
本文介绍了R :给定一组索引更新向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量(初始化为零)和该向量的一组索引.对于索引中的每个值,我想增加向量中的相应索引.所以,假设 6 在索引中出现两次(如下例所示),那么向量的第 6 个元素的值应该是 2.

I have a vector (initialized to zeros) and a set of indices of that vector. For each value in indices, I want to increment the corresponding index in the vector. So, say 6 occurs twice in indices (as in the example below), then the value of the 6th element of the vector should be 2.

例如:

> 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

不使用循环的最惯用的方法是什么?

What is the most idiomatic way of doing this without using loops?

推荐答案

tabulate 函数就是为此而生的

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

这篇关于R :给定一组索引更新向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆