Search code examples
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:

    • pattern the pattern to be replaced - i.e. "_Part"
    • replacement the string to be used as replacement - i.e. the empty string ""
    • x the string we want to replace something in - i.e. the rownames

    An additional argument (not in the first 3):

    • fixed indicating if pattern is meant to be a regular expression or "just" an ordinary string - i.e. just a string