Copy one vector to another, omitting the NA values

How can I selectively rewrite an old vector? I want to add 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 finish 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 to do the same.

+4
source share
3 answers

You can use something like this:

old.vector<-ifelse(is.na(replacement.values),old.vector,replacement.values)

And old.vectorthen it looks like

old.vector
[1] "x" "y" "3" "z" "5"

If the vectors have a consistent length.

+2
source

Another, similar to the Luces method, would be a simple indx replacement

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]
+3
source
idx <- is.na(replacement.values)
replace(replacement.values, idx, old.vector[idx])
# [1] "x" "y" "3" "z" "5"
+2

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


All Articles