Goutham
Goutham

Reputation: 2859

R : Updating a vector given a set of indices

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.

Eg:

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

The updated vector should be

> 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?

Upvotes: 0

Views: 109

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

You can use rle for this:

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

Upvotes: 0

Andrey Shabalin
Andrey Shabalin

Reputation: 4614

The function tabulate is made for that

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

Upvotes: 4

Related Questions