How can I selectively over-write the old vector? I want to add in the replacement values, but only where they are not = NA
.
So starting with this data:
old.vector <- 1:5
replacement.values <- c('x', 'y', NA, 'z', NA)
I want to end up with this vector:
new.vector: c('x', 'y', 3, 'z', 5)
edit: Thanks for the welcome and help. It's great to see a bunch of different ways of doing the same thing.
Another similar to Lukes way would be just simple replacement by indx
indx <- is.na(replacement.values)
replacement.values[indx] <- old.vector[indx]
## [1] "x" "y" "3" "z" "5"
Or you can do it the other way around (as suggested by @RusanKax)
indx <- !is.na(replacement.values)
old.vector[indx] <- replacement.values[indx]
You could use something like this, also:
old.vector<-ifelse(is.na(replacement.values),old.vector,replacement.values)
And old.vector
then looks like
old.vector
[1] "x" "y" "3" "z" "5"
If the vectors are of compatible length.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With