yrx1702
yrx1702

Reputation: 1641

Combine character matrices into one

Given two matrices

a <- matrix(c("a","","","d"),2,2)
b <- matrix(c("","b","",""),2,2)

a
     [,1] [,2]
[1,] "a"  ""  
[2,] ""   "d" 
b
     [,1] [,2]
[1,] ""   ""  
[2,] "b"  ""  

Is there an easy way to combine these two into one and get

     [,1] [,2]
[1,] "a"   ""  
[2,] "b"  "d"  

without looping over each individual element?

I am interested in the problem of this "merge" in general. However, for the time being, each cell is non-empty in only one of those matrices (i.e., the case where cell [1,1] contains something in matrix a and in matrix b is ruled out).

Upvotes: 0

Views: 77

Answers (3)

akrun
akrun

Reputation: 887431

We can also use. case_when

library(dplyr)
case_when(a== '' ~ b, TRUE ~ a)

Upvotes: 0

lroha
lroha

Reputation: 34556

You can also do:

a[a == "" & b != ""] <- b[b != ""]
a
     [,1] [,2]
[1,] "a"  ""  
[2,] "b"  "d" 

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389095

If two matrices are of same dimension we can do :

ifelse(a == '', b, a)

#    [,1] [,2]
#[1,] "a"  ""  
#[2,] "b"  "d" 

Upvotes: 4

Related Questions