How to match two vectors with missing values?

I have two vectors of the same length and I am trying to combine them so that they fill in the missing values. For example:

a=c("",1,2,"")
b=c(5,"","",6)

      

I am looking for this output:

5 1 2 6

      

Thank you so much

+3


source to share


5 answers


In this case, normal numeric comparison via pmax

also works:

as.numeric(pmax(a,b))
#[1] 5 1 2 6

      



This is because R resorts to alphanumeric sorting when max

/ min

etc. apply to character data:

max(c("b","a"))
#[1] "b"

      

+5


source


and



as.numeric(paste(a,b))
[1] 5 1 2 6

      

+5


source


Or:

a[a==""] <- b[b!=""]
as.numeric(a)
# [1] 5 1 2 6

      

+4


source


a[a == ""] <- 0
b[b == ""] <- 0

a <- as.numeric(a)
b <- as.numeric(b)

output <- a + b

      

+3


source


as.numeric(ifelse(a != "", a, b))

      

+3


source







All Articles