0

I am working on a two columns dataset in R representing response values ("Response") of different samples belonging to different groups ("Group") and I want to create a third ID column to identify each sample with a number from 1 to [..] (there is not the same number of sample in each group). Here is just a few lines as an example: Example

Thanks for your help.

Romain
  • 5
  • 1
  • 1
    Does this answer your question? [Numbering rows within groups in a data frame](https://stackoverflow.com/questions/12925063/numbering-rows-within-groups-in-a-data-frame) – user438383 Jun 02 '21 at 10:43

2 Answers2

0

try

library(tidyverse)
your_data %>%
  group_by(Group)%>%
  mutate(ID = 1:n())
L Smeets
  • 888
  • 4
  • 17
0

We could use cur_group_id

library(dplyr)
df %>% 
  group_by(Group) %>% 
  mutate(new_id = cur_group_id())

Output:

  Group Response    Id new_id
  <chr>    <dbl> <dbl>  <int>
1 A          1.5     1      1
2 A          3.4     2      1
3 A          2.3     3      1
4 A          1.8     4      1
5 B          1.9     1      2
6 B          1.4     2      2
7 C          2.7     1      3
8 C          2.3     2      3
9 C          3.2     3      3
TarJae
  • 72,363
  • 6
  • 19
  • 66