按两列提取匹配

问题描述 投票:0回答:0

我有一个这样的数据框:

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)
r dplyr
© www.soinside.com 2019 - 2024. All rights reserved.