Create a group ID based on a string column in R

Viewed 94

This is probably a dumb question, but how do I create a new group ID based on a string column in R? The values of the ID are arbitrary.

ID: the column I want to create

    Name      ID  
   A09john    1     
   J43mary    2     
   B7you      3     
   A09john    1     
   J43mary    2     
   B7you      3     

I was hoping to use simple codes like below, but I don't know how to do it. Thank you!

df1 %>% 
  group_by(Name) %>% 
  mutate(ID = row_number(as.numeric(????)))
1 Answers

Here is a tidyverse approach that use dplyr::cur_group_id() (current group identifier)

library(tidyverse)
d <- data.frame(
  Name = c("A09john", "J43mary", "B7you", "A09john",  "J43mary", "B7you")
)

new_data <- d |> 
  dplyr::group_by(Name) |> 
  dplyr::mutate(ID = dplyr::cur_group_id()) |> 
  ungroup()

new_data
#> # A tibble: 6 x 2
#>   Name       ID
#>   <chr>   <int>
#> 1 A09john     1
#> 2 J43mary     3
#> 3 B7you       2
#> 4 A09john     1
#> 5 J43mary     3
#> 6 B7you       2

# If you want to have the ID based on the order of appearance.
# You have to convert Name to factor first

new_data2 <- d |> 
  dplyr::mutate(Name = factor(Name, levels = unique(Name))) |> 
  dplyr::group_by(Name) |> 
  mutate(ID = dplyr::cur_group_id()) |>
  ungroup()

new_data2
#> # A tibble: 6 x 2
#> # Groups:   Name [3]
#>   Name       ID
#>   <fct>   <int>
#> 1 A09john     1
#> 2 J43mary     2
#> 3 B7you       3
#> 4 A09john     1
#> 5 J43mary     2
#> 6 B7you       3

Created on 2022-06-16 by the reprex package (v2.0.1)

row_number() is not the solution as it will compute the row number in each group.

Related