문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top