Create consecutive new ID for multiple factors

48 Views Asked by At

I have a dataframe:

mydata = data.frame(Species   = rep(letters[1:3], each = 20),
                    Prey = rep(round(runif(12)*1000, 0), each = 5))

Now I would like to give each row in the column "Species" unique number (so a, b, c etc.) with each unique "Prey". So for instance we have species a and we have 4 different Prey. then I would like to have a1, a2, a3,a4,a5 for each Prey. So we have a unique combination of Species and Prey for each "a" species.

For prey 128 in a:a1,a2,a3,a4,a5
For prey 362 in a:a1,a2,a3,a4,a5

This is the same for the next species, but then with Species "b".

I already tried something like this. But the numbers for each unique Prey should be consecutive.

tmp <- mydata %>% 
  group_by(Species) %>% 
  mutate(ID = str_c(Species, as.numeric(as.factor(Prey)), sep = "."))

I hope I am clear.

Thank you in advance.

2

There are 2 best solutions below

0
Ramiro Magno On
library(tidyverse)

mydata = data.frame(Species   = rep(letters[1:3], each = 20),
                    Prey = rep(round(runif(12)*1000, 0), each = 5))

mydata2 <-
  mydata |>
  group_by(Species) |>
  mutate(ID = paste(Species, seq_len(n()), sep = "."))

mydata2
#> # A tibble: 60 × 3
#> # Groups:   Species [3]
#>    Species  Prey ID   
#>    <chr>   <dbl> <chr>
#>  1 a         962 a.1  
#>  2 a         962 a.2  
#>  3 a         962 a.3  
#>  4 a         962 a.4  
#>  5 a         962 a.5  
#>  6 a         337 a.6  
#>  7 a         337 a.7  
#>  8 a         337 a.8  
#>  9 a         337 a.9  
#> 10 a         337 a.10 
#> # ℹ 50 more rows
0
Zhiqiang Wang On

try this:

mydata %>% group_by(Species, Prey) %>% 
    mutate(id = paste0(Species, ".", row_number()))