R filling vector

I have a vector of zeros, such as length 10. So,

v = rep(0,10) 

I want to fill in some values ​​of a vector based on a set of indices in v1 and another vector v2 that actually has values ​​in the sequence. So for another vector v1 the indices 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 indices in v1 were mapped from v2, and the rest were equal to 0. I obviously can write a for loop, but this is too long in R due to the length of the actual matrices. Any easy way to do this?

+4
source share
2 answers

You can assign it as follows:

 v[v1] = v2 

For instance:

 > 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 
+5
source

You can also do this 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 more details.

+2
source

Source: https://habr.com/ru/post/1445591/


All Articles