Biochem
Biochem

Reputation: 361

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?

Upvotes: 0

Views: 7243

Answers (2)

akrun
akrun

Reputation: 887781

We could just use as.character and it will remove the trailing 0s

df_view$Score <- as.character(df$Score)
df_view$Score
#[1] "15.401"  "5.1188"  "15.045"  "3.0408"  "0.28143" "19.792" 

data

df_view <- 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)

Upvotes: 5

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522581

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)

Upvotes: 5

Related Questions