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
In this case, normal numeric comparison via pmax also works:
pmax
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
min
max(c("b","a")) #[1] "b"
and
as.numeric(paste(a,b)) [1] 5 1 2 6
Or:
a[a==""] <- b[b!=""] as.numeric(a) # [1] 5 1 2 6
a[a == ""] <- 0 b[b == ""] <- 0 a <- as.numeric(a) b <- as.numeric(b) output <- a + b
as.numeric(ifelse(a != "", a, b))