我有一个这样的数据框:
ID | col1 | col2 |
---|---|---|
AB | 1 | 3 |
AB | 1 | 1 |
光盘 | 2 | 4 |
光盘 | 2 | 3 |
我想比较每个 ID 中的行。 对于每个有差异的列,添加不匹配项。
输出:
ID | col1 | col2 | match_extract_col1 | match_extract_col2 | match_extract_col1_2 |
---|---|---|---|---|---|
AB | 1 | 3 | 钠 | 钠 | 1:1 |
AB | 0 | 1 | 钠 | 钠 | 1:1 |
光盘 | 2 | 4 | 2:2 | 钠 | 钠 |
光盘 | 2 | 3 | 2:2 | 钠 | 钠 |
例如,我有一个这样的命令,只能逐列检查:
library(dplyr)
df %>%
mutate(across(col1:col2, ~ if_else(n_distinct(.x) == 1, NA, toString(.x)),
.names = "match_extract_{.col}"),
.by = ID)