r-创建两个数据帧之间匹配和不匹配的数据帧



我正在尝试创建一个热图,以便可视化一些预测值和预期值之间的匹配和不匹配。

如果a是包含预测值的数据帧,b是预期值;

a = rbind (sample(0:1, size=14, replace = T),sample(0:1, size=14, replace = T))
b = rbind (sample(0:1, size=40, replace = T),sample(0:1, size=40, replace = T))

如何创建仅包含&b并返回

  • 当两个数据帧中的某个值相同时
  • 另一个值,如果预测值为0而预期值为1
  • 如果预测值为1而预期值为0,则为另一个值
## your example data are matrices, 
## let's make them data frames:
a = as.data.frame(a)
b = as.data.frame(b)
common_cols = intersect(names(a), names(b))
## see where they are equal
## TRUE means equal, FALSE means not equal
a[common_cols] == b[common_cols]
#         V1   V2    V3   V4    V5    V6   V7    V8    V9   V10   V11   V12   V13  V14
# [1,]  TRUE TRUE FALSE TRUE FALSE FALSE TRUE FALSE  TRUE FALSE FALSE  TRUE FALSE TRUE
# [2,] FALSE TRUE  TRUE TRUE  TRUE FALSE TRUE  TRUE FALSE  TRUE FALSE FALSE  TRUE TRUE
## see the difference
## 0 means a and b are equal
## 1 means a is 1 and b is 0
## -1 means a is 0 and b is 1
a[common_cols] - b[common_cols]
#   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14
# 1  0  0 -1  0  1 -1  0  1  0  -1   1   0  -1   0
# 2  1  0  0  0  0  1  0  0 -1   0  -1  -1   0   0