Search code examples
rdataframeformattingdigits

How to remove trailing zeros in R dataframe


I have a R data.frame that looks like this:

   Gene    Score
1  AAT2 15.40100
2  ACB1  5.11880
3  ACF2 15.04500
4 ADE16  3.04080
5 ADE17  0.28143
6  ADE4 19.79200

However I need to get rid of the trailing zeros in order to get:

   Gene    Score
1  AAT2 15.401
2  ACB1  5.1188
3  ACF2 15.045
4 ADE16  3.0408
5 ADE17  0.28143
6  ADE4 19.792

Basically I am trying to set the number of digits in the score column to 5 digits; I specifically want the data to be viewed in that way. How can I do this in R?


Solution

  • If you want to view your Score data as text, with no trailing zeroes, then use:

    df_view <- df[c("Gene", "Score")]
    df_view$Score <- sub("0+$", "", as.character(df_view$Score))
    
    df_view
    
       Gene   Score
    1  AAT2  15.401
    2  ACB1  5.1188
    3  ACF2  15.045
    4 ADE16  3.0408
    5 ADE17 0.28143
    6  ADE4  19.792
    

    Data:

    df <- data.frame(Gene=c("AAT2", "ACB1", "ACF2", "ADE16", "ADE17", "ADE4"),
                     Score=c(15.40100, 5.11880, 15.04500, 3.04080, 0.28143, 19.79200),
                     stringsAsFactors=FALSE)