提取组之间的不匹配。

huangapple go评论97阅读模式
英文:

Extract mismatch by groups

问题

  1. 我有一个如下的数据框:
  2. | ID | col1| col2 |
  3. |:---- |:------:| -----:|
  4. | AB |1 | 3 |
  5. | AB |1 | 3 |
  6. | CD |2 | 4 |
  7. | CD |2 | 3 |
  8. 我想比较每个ID内的行。
  9. 对于每个有差异的列,将不匹配的内容添加到相应的列中。
  10. 输出:
  11. | ID | col1| col2 | 不匹配提取_col1| 不匹配提取_col2|
  12. |:---- |:------:| :-----:| :-----:|-----:|
  13. | AB |1 | 3 |Na |Na|
  14. | AB |1 | 3 |Na| Na|
  15. | CD |2 | 4 |Na| 4:3|
  16. | CD |2 | 3 |Na| 4:3|
英文:

I have a data frame like this:

ID col1 col2
AB 1 3
AB 1 3
CD 2 4
CD 2 3

I would like to compare row within each ID.
For each column with difference add in the mismatch referred to the column.

Output:

ID col1 col2 mismatch_extract_col1 mismatch_extract_col2
AB 1 3 Na Na
AB 1 3 Na Na
CD 2 4 Na 4:3
CD 2 3 Na 4:3

答案1

得分: 2

您可以使用n_distinct() == 1来确定是否在每个ID组的每一列中存在不匹配。

  1. library(dplyr)
  2. df %>%
  3. mutate(across(col1:col2, ~ if_else(n_distinct(.x) == 1, NA, toString(.x)),
  4. .names = "mismatch_extract_{.col}"),
  5. .by = ID)
  6. # # A tibble: 4 × 5
  7. # ID col1 col2 mismatch_extract_col1 mismatch_extract_col2
  8. # <chr> <int> <int> <lgl> <chr>
  9. # 1 AB 1 3 NA NA
  10. # 2 AB 1 3 NA NA
  11. # 3 CD 2 4 NA 4, 3
  12. # 4 CD 2 3 NA 4, 3

注意:代码部分已排除在翻译之外,只提供翻译的文本。

英文:

You can use n_distinct() == 1 to know if there is a mismatch in each column by ID groups.

  1. library(dplyr)
  2. df %&gt;%
  3. mutate(across(col1:col2, ~ if_else(n_distinct(.x) == 1, NA, toString(.x)),
  4. .names = &quot;mismatch_extract_{.col}&quot;),
  5. .by = ID)
  6. # # A tibble: 4 &#215; 5
  7. # ID col1 col2 mismatch_extract_col1 mismatch_extract_col2
  8. # &lt;chr&gt; &lt;int&gt; &lt;int&gt; &lt;lgl&gt; &lt;chr&gt;
  9. # 1 AB 1 3 NA NA
  10. # 2 AB 1 3 NA NA
  11. # 3 CD 2 4 NA 4, 3
  12. # 4 CD 2 3 NA 4, 3

huangapple
  • 本文由 发表于 2023年2月14日 21:47:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定