R populating a vector

ganesh reddy picture ganesh reddy · Nov 12, 2012 · Viewed 16.2k times · Source

I have a vector of zeros, say of length 10. So

v = rep(0,10)

I want to populate some values of the vector, on the basis of a set of indexes in v1 and another vector v2 that actually has the values in sequence. So another vector v1 has the indexes say

v1 = c(1,2,3,7,8,9)

and

v2 = c(0.1,0.3,0.4,0.5,0.1,0.9)

In the end I want

v = c(0.1,0.3,0.4,0,0,0,0.5,0.1,0.9,0)

So the indexes in v1 got mapped from v2 and the remaining ones were 0. I can obviously write a for loop but thats taking too long in R, owing to the length of the actual matrices. Any simple way to do this?

Answer

David Robinson picture David Robinson · Nov 12, 2012

You can assign it this way:

v[v1] = v2

For example:

> v = rep(0,10)
> v1 = c(1,2,3,7,8,9)
> v2 = c(0.1,0.3,0.4,0.5,0.1,0.9)
> v[v1] = v2
> v
 [1] 0.1 0.3 0.4 0.0 0.0 0.0 0.5 0.1 0.9 0.0