Reputation: 105
I have 2 different vectors in R. The entries in the first one are only 0 or 1. The length of the second vector is equal to the number of 1's in the first vector. I want an output that is the first vector but with the 1's replaced by the entries of the 3rd vector. E.g.
v1<-c(1,0,0,1,1)
v2<-c(2,3,4)
I want:
v3<-c(2,0,0,3,4)
The length of v1 will be 10 in my script and I have over 1000 to compute so it is not possible to do it manually. Any ideas would be great, thanks!
Jonny
Upvotes: 1
Views: 1110
Reputation: 89057
Like suggested, you can do:
v1[as.logical(v1)] <- v2
but it has the disadvantage of overwriting v1
. If you don't want that, you can do:
v3 <- replace(v1, as.logical(v1), v2)
Or this one, which is a little more obscure:
v3 <- `[<-`(v1, as.logical(v1), v2)
Upvotes: 1