如何删除 R 数据框中的尾随零

How to remove trailing zeros in R dataframe

我有一个 R data.frame 看起来像这样:

   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

但是我需要去掉尾随的零才能得到:

   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

基本上我试图将分数列中的位数设置为 5 位数。我如何在 R 中执行此操作?

如果您想查看您的Score数据为文本,不带尾随零,请使用:

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

数据:

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)

我们可以只使用 as.character,它会删除尾随的 0

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

数据

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)