Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two vectors by non NA values [duplicate]

Tags:

r

na

vector

Possible Duplicate:
Combining two vectors element-by-element

I have two vectors

d = c(1, 2, NA, NA)
c = c(NA, NA, 1, NA)

How can I get an output that would combine the non NAs as follows?

[1] 1 2  1 NA

thanks

like image 288
jamborta Avatar asked Nov 28 '12 11:11

jamborta


2 Answers

pmin(d, c, na.rm = TRUE)

will do the trick.

[1]  1  2  1 NA
like image 160
Sven Hohenstein Avatar answered Sep 28 '22 01:09

Sven Hohenstein


What you are asking is a bit vague. For example, what happens if you neither element is a NA?

Anyway, here's one method that gives the desired result:

##Don't name things c - it's confusing.
d1 = c(1,2,NA,NA)
d2 = c(NA,NA,1,NA)

d1[is.na(d1)] = d2[is.na(d1)]

Which gives:

R> d1
[1]  1  2  1 NA
like image 39
csgillespie Avatar answered Sep 27 '22 23:09

csgillespie