Search code examples
rrenamerows

Is there a function in R to rename rows by groups with increasing numbers


I have a very simple data frame [36, 4], and I'd like to rename rows of one column: see column "Ab_type" in the attached image

I'd like to rename the 36 rows of column "Ab_type" by groups of 4 (e.g. Ab1_1, Ab1_2, Ab1_3, Ab1_4, Ab2_1, Ab2_2, Ab2_3, Ab2_4,....Isotype_1, Isotype_2, Isotype_3, Isotype_4).

Would you have any suggestion? I'm completely new to coding. Many thanks in advance.

enter image description here


Solution

  • We can use

    df1$Ab_type <- sub("-", "", sub("-[^-]+$", "", df1$Ab_type))
    df1$Ab_type <- with(df1, paste0(Ab_type, "_", 
         ave(seq_along(Ab_type), Ab_type, FUN = seq_along)))