【问题标题】:Assign unique ID based on values in EITHER of two columns根据两列中的任意一个中的值分配唯一 ID
【发布时间】:2020-12-15 16:34:56
【问题描述】:

这不是 this question 的重复。请在标记重复之前完整阅读问题。

我有一个这样的data.frame:

library(tidyverse)

tibble(
  color = c("blue", "blue", "red", "green", "purple"),
  shape = c("triangle", "square", "circle", "hexagon", "hexagon")
)

  color  shape   
  <chr>  <chr>   
1 blue   triangle
2 blue   square  
3 red    circle  
4 green  hexagon 
5 purple hexagon 

我想像这样添加group_id 列:

  color  shape    group_id
  <chr>  <chr>       <dbl>
1 blue   triangle        1
2 blue   square          1
3 red    circle          2
4 green  hexagon         3
5 purple hexagon         3

困难在于我想按 color shape 的唯一值进行分组。我怀疑解决方案可能是使用列表列,但我不知道如何。

【问题讨论】:

  • 谢谢,@akrun。你的回答很有帮助。我真的认为其他用户会有足够高的阅读理解能力来识别这是与重复报告中链接的基本 group_by 问题不同的问题。
  • 确保人们准确理解您的要求是查看您尝试过的内容很有帮助的原因之一。即使您的代码不起作用,这也可以显示您对问题的处理方法
  • 顺便说一句,您可以@ notify gold badge holders 单方面关闭问题作为问题的 cmets 中的重复项。除非他们关注您的问题(不太可能),否则编辑您的问题不会通知他们。我同意你的观点,这不是目标的重复,所以我投票重新开放。

标签: r dplyr


【解决方案1】:

我们可以在base R中使用duplicated

df1$group_id <- cumsum(!Reduce(`|`, lapply(df1, duplicated)))

-输出

df1
# A tibble: 5 x 3
#  color  shape    group_id
#  <chr>  <chr>       <int>
#1 blue   triangle        1
#2 blue   square          1
#3 red    circle          2
#4 green  hexagon         3
#5 purple hexagon         3

或使用tidyverse

library(dplyr)
library(purrr)
df1 %>%
    mutate(group_id = map(.,  duplicated) %>%
                         reduce(`|`) %>%
                         `!` %>% 
                       cumsum)

数据

df1 <- structure(list(color = c("blue", "blue", "red", "green", "purple"
), shape = c("triangle", "square", "circle", "hexagon", "hexagon"
)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))

【讨论】:

  • 仅供参考,请查看this question 以进一步讨论否定! 与管道%&gt;%
猜你喜欢
  • 2017-08-12
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
  • 2013-05-08
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多