简体   繁体   English

为什么 R format() function 无法正常工作以格式化数字向量?

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

This should be very simple.这应该很简单。 This 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"

When passed through format(test, digits = 2, scientific = FALSE) should give 2 decimals.通过format(test, digits = 2, scientific = FALSE)应该给出 2 位小数。

Instead, I have this:相反,我有这个:

 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"

No idea what is going on.不知道发生了什么。 I'm in Rstudio 1.4.1103 with R 4.0.3 on macOS Mojave 10.14.6.我在 macOS Mojave 10.14.6 上使用 Rstudio 1.4.1103 和 R 4.0.3。 How to "force" format to just print 2 decimals instead of making sure there would be minimum 2 decimals as in "0.000083"?如何“强制”格式只打印 2 个小数,而不是确保至少有 2 个小数,如“0.000083”?

You can use round() to round numbers, giving the vector's name and number of decimals, eg:您可以使用round()对数字进行四舍五入,给出向量的名称和小数位数,例如:

round(test, 2)

I usually prefer sprintf for formatting numbers.我通常更喜欢sprintf来格式化数字。 Gives a lot more control.提供了更多的控制权。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM