Przypisz niepowtarzalny identyfikator na podstawie wartości z KAŻDEJ dwóch kolumn

Dec 16 2020

To nie jest duplikat tego pytania . Przeczytaj pytania w całości przed oznaczeniem duplikatów.

Mam taką ramkę 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 

Chciałbym dodać taką group_idkolumnę:

  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

Trudność polega na tym, że chcę grupować według unikalnych wartości color lub shape . Podejrzewam, że rozwiązaniem może być użycie kolumn list, ale nie mogę dowiedzieć się, jak to zrobić.

Odpowiedzi

2 akrun Dec 15 2020 at 23:35

Możemy użyć duplicatedwbase R

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

-wynik

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

Lub używając tidyverse

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

dane

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"
))