R populating a vector [duplicate]

2019-06-20 06:13发布

问题:

This question already has an answer here:

  • R fill vector efficiently 4 answers

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?

回答1:

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


回答2:

You can also do it with replace

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)

replace(v, v1, v2)
[1] 0.1 0.3 0.4 0.0 0.0 0.0 0.5 0.1 0.9 0.0

See ?replace for details.