How to create a column with the serial number of values in character column of an R data frame?



A group column in an R data frame have duplicate values and we might want to create a column with the serial number based on the values such as first value of the first group gets 1, the same value gets 2 when occurred second time in the same column and so on. This can be done by using ave function as shown in the below examples.

Example

Consider the below data frame −

 Live Demo

S.No<-1:20 Group<-sample(LETTERS[1:4],20,replace=TRUE) df1<-data.frame(S.No,Group) df1

Output

S.No Group 1  1 B 2  2 A 3  3 C 4  4 C 5  5 B 6  6 C 7  7 C 8  8 C 9  9 D 10 10 D 11 11 C 12 12 C 13 13 A 14 14 B 15 15 A 16 16 D 17 17 C 18 18 B 19 19 A 20 20 C

Creating a column for serial numbers of group values in df1 −

Example

df1$GroupWise_SerialNo<-with(df1,ave(as.character(Group),Group,FUN=seq_along)) df1

Output

S.No Group GroupWise_SerialNo 1  1    B    1 2  2    A    1 3  3    C    1   4  4    C    2 5  5    B    2 6  6    C    3 7  7    C    4 8  8    C    5 9  9    D    1 10 10    D    2 11 11    C    6 12 12    C    7 13 13    A    2 14 14    B    3 15 15    A    3 16 16    D    3 17 17    C    8 18 18    B    4 19 19    A    4 20 20    C    9

Example

 Live Demo

ID<-1:20 Sample<-sample(c("India","China","UK"),20,replace=TRUE) df2<-data.frame(ID,Sample) df2

Output

   ID Sample 1  1 India 2  2 China 3  3 China 4  4 UK 5  5 China 6  6 UK 7  7 India 8  8 India 9  9 UK 10 10 India 11 11 UK 12 12 India 13 13 UK 14 14 UK 15 15 UK 16 16 India 17 17 India 18 18 UK 19 19 UK 20 20 China

Creating a column for serial numbers of group values in df2 −

Example

df2$SampleWise_Numbering<- with(df2,ave(as.character(Sample),Sample,FUN=seq_along)) df2

Output

   ID Sample SampleWise_Numbering 1  1 India    1 2  2 China    1 3  3 China    2 4  4 UK       1 5  5 China    3 6  6 UK       2 7  7 India    2 8  8 India    3 9  9 UK       3 10 10 India    4 11 11 UK       4 12 12 India    5 13 13 UK       5 14 14 UK       6 15 15 UK       7 16 16 India    6 17 17 India    7 18 18 UK       8 19 19 UK       9 20 20 China    4
Updated on: 2020-12-05T13:25:08+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements