Let's say I have two vectors, one that includes NA values, and another that is the length of the first vector after dropping the NA values. I am looking to insert the NA values from the first vector into the second vector, while keeping the position of the NA values the same.
a<-c(1,2,3,6,5,NA,4,5,NA,45,6,NA)
b<-c(1,2,4,3,6,5,7,8,40)
This can be done by concatenating each component, but this seems extremely tedious, especially since my data are much more complicated than the above example. Something like
b[which(is.na(a))]<-NA
is what I am looking for, but this of course replaces elements instead of inserting elements like I want. I am at a loss for this even though it seems relatively simple.
CodePudding user response:
Create a NA vector of the same length as 'a' and then replace based on the non NA elements in 'a'
b <- replace(rep(NA, length(a)), !is.na(a), b)
-output
b
#[1] 1 2 4 3 6 NA 5 7 NA 8 40 NA
Or more compactly, do the replace on 'a'
replace(a, !is.na(a), b)
[1] 1 2 4 3 6 NA 5 7 NA 8 40 NA
