给出两个矩阵
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
中的值的情况)
答案 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)