rr-rownames

Rename rownames


I would like to rename row names by removing common part of a row name

          a b  c
CDA_Part  1 4  4
CDZ_Part  3 4  4
CDX_Part  1 4  4

result

     a b  c
CDA  1 4  4
CDZ  3 4  4
CDX  1 4  4

Solution

  • 1.Create a minimal reproducible example:

    df <- data.frame(a = 1:3, b = 4:6)
    rownames(df) <- c("CDA_Part", "CDZ_Part", "CDX_Part")
    
    df
    

    Returns:

             a b
    CDA_Part 1 4
    CDZ_Part 2 5
    CDX_Part 3 6
    

    2.Suggested solution using base Rs gsub:

    rownames(df) <- gsub("_Part", "", rownames(df), fixed=TRUE)
    
    df
    

    Returns:

        a b
    CDA 1 4
    CDZ 2 5
    CDX 3 6
    

    Explanation:

    gsub uses regex to identify and replace parts of strings. The three first arguments are:

    An additional argument (not in the first 3):