将字符矩阵合并为一个

时间:2020-05-12 08:41:10

标签: r matrix

给出两个矩阵

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"  ""  

有没有一种简单的方法可以将这两个结合在一起并获得

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

是否没有遍历每个单独的元素?

我通常对这个“合并”的问题感兴趣。但是,目前,每个单元格仅在那些矩阵之一中是非空的(即,确定了单元格[1,1]包含矩阵a和矩阵b中的值的情况)

3 个答案:

答案 0 :(得分:4)

如果两个矩阵的维数相同,我们可以这样做:

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

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

答案 1 :(得分:1)

您也可以这样做:

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

答案 2 :(得分:0)

我们也可以使用。 case_when

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