为什么 R format() 函数不能正常工作以格式化数字向量?

Why R format() function is not working properly to format a numeric vector?

这个应该很简单。这个向量:

test = c(0.027, 0.01872169, 0.1869244, 0.6997091, 0.06764486, 0.1436803, 
0.001610974, 0.5461064, 0.3066009, 0.002001355, 0.03864836, 0.391397, 
0.5145854, 0.05524137, 0.01838195, 0.02019719, 0.346739, 0.5876818, 
0.02694247, 8.277247e-05, 0.1929826, 0.7863224, 0.02061222)

class(test)
[1] "numeric"

通过时 format(test, digits = 2, scientific = FALSE) 应给出 2 位小数。

相反,我有这个:

 format(test, digits = 2, scientific = FALSE)
 [1] "0.027000" "0.018722" "0.186924" "0.699709" "0.067645" "0.143680" "0.001611" "0.546106" "0.306601" "0.002001" "0.038648" "0.391397" "0.514585" "0.055241" "0.018382"
[16] "0.020197" "0.346739" "0.587682" "0.026942" "0.000083" "0.192983" "0.786322" "0.020612"

不知道发生了什么。我在 macOS Mojave 10.14.6 上使用 Rstudio 1.4.1103 和 R 4.0.3。如何“强制”格式只打印 2 位小数而不是像“0.000083”那样确保至少有 2 位小数?

您可以使用 round() 对数字进行舍入,给出向量的名称和小数位数,例如:

round(test, 2)

我通常更喜欢 sprintf 格式化数字。提供更多控制权。

sprintf(test, fmt = "%0.2f")
# [1] "0.03" "0.02" "0.19" "0.70" "0.07" "0.14" "0.00" "0.55" "0.31" "0.00" "0.04" "0.39" "0.51" "0.06" "0.02" "0.02" "0.35" "0.59"
# [19] "0.03" "0.00" "0.19" "0.79" "0.02"