Reputation: 1641
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
Reputation: 887431
We can also use. case_when
library(dplyr)
case_when(a== '' ~ b, TRUE ~ a)
Upvotes: 0
Reputation: 34556
You can also do:
a[a == "" & b != ""] <- b[b != ""]
a
[,1] [,2]
[1,] "a" ""
[2,] "b" "d"
Upvotes: 1
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