簡體   English   中英

根據兩列中任意一個中的值分配唯一 ID

[英]Assign unique ID based on values in EITHER of two columns

這不是這個問題的重復。 在標記重復項之前,請完整閱讀問題。

我有一個這樣的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

困難在於我想按colorshape的獨特值進行分組。 我懷疑解決方案可能是使用列表列,但我不知道如何。

我們可以在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"
))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM