Reputation: 75
I would like to merge two character vectors into one by the following logic:
A <- c("005", "NA", "100", "NA")
B <- c("005", "NA", "NA", "257")
C <- c("005", "NA", "100", "257")
Let's say I have vector A
and B
and I want to merge them in such a way that I get vector C
, how can I achieve that?
Upvotes: 3
Views: 4338
Reputation: 39154
We can use coalesce
from the dplyr
package, but notice that you need to replace "NA" to NA
as in R they are different. Here I convert both A
and B
to numeric to achieve this.
library(dplyr)
A <- c("005", "NA", "100", "NA")
B <- c("005", "NA", "NA", "257")
A <- as.numeric(A)
B <- as.numeric(B)
coalesce(A, B)
# [1] 5 NA 100 257
Upvotes: 3
Reputation: 32548
replace(A, A == "NA", B[A == "NA"])
#[1] "005" "NA" "100" "257"
OR
temp = cbind(A, B)
temp[cbind(seq_along(A),
match(colnames(temp)[max.col(temp != "NA")], colnames(temp)))]
#[1] "005" "NA" "100" "257"
If you have NA
as opposed to "NA"
, then change
A == "NA"
to is.na(A)
temp != "NA"
to !is.na(temp)
Upvotes: 2
Reputation: 388817
You could do
C <- A
C[A == "NA"] <- B[A == "NA"]
C
#[1] "005" "NA" "100" "257"
Upvotes: 2