Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy one vector to another, omitting NA values

Tags:

r

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.

like image 438
Locutus Avatar asked Mar 17 '23 09:03

Locutus


2 Answers

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]
like image 79
David Arenburg Avatar answered Mar 20 '23 14:03

David Arenburg


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.

like image 41
Rusan Kax Avatar answered Mar 20 '23 14:03

Rusan Kax