R populating a vector [duplicate]

耗尽温柔 提交于 2019-12-10 13:14:42

问题


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.



来源:https://stackoverflow.com/questions/13349613/r-populating-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!