Niklas
Niklas

Reputation: 75

Combine two vectors into one in R

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

Answers (3)

www
www

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

d.b
d.b

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

  1. A == "NA" to is.na(A)
  2. temp != "NA" to !is.na(temp)

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388817

You could do

C <- A
C[A == "NA"] <- B[A == "NA"]
C
#[1] "005" "NA"  "100" "257"

Upvotes: 2

Related Questions