如何告诉 R 正确舍入? [英] How can I tell R to round correctly?
问题描述
如何告诉 R 正确舍入?
How can I tell R to round correctly?
R 中的小数位我遇到了一个我不知道如何解决的问题我想让 R 计算 5/26*100 = 19.230769
Decimal Places in R I have encountered a problem that I cannot figure out how to solve I want R to calculate 5/26*100 = 19.230769
x <- 5/26*100
x
给我:
[1] 19.23077
让我们尝试使用round(),首先将数字设置为4:
Let's try to use round(), first setting the digits to 4:
x <- round(5/26*100,digits=4)
x
给出:
[1] 19.2308
接下来,让我们将数字设置为 5:
Next, let's set the digits to 5:
x <- round(5/26*100,digits=5)
x
给出:
[1] 19.23077
现在,让我们将数字设置为 6:
Now, let's set the digits to 6:
x <- round(5/26*100,digits=6)
x
给出:
[1] 19.23077
谁能告诉我如何解决这个问题?您是否得到相同的结果,或者您的 rstudio 是否正确舍入?
Can anyone tell me how to fix this? Do you get the same results, or does your rstudio round correctly?
我也累了signif()
I have also tired signif()
x <- signif(5/26*100,digits=6)
x
给我们:
[1] 19.2308
增加到 7 位数:
> x <- signif(5/26*100,digits=7)
> x
[1] 19.23077
增加到 8 位:
> x <- signif(5/26*100,digits=8)
> x
[1] 19.23077
我们可以使用 sprintf()
And we can use sprintf()
> x <- sprintf("%0.6f", (5/26*100))
> x
[1] "19.230769"
sprintf() 通过四舍五入解决了问题,但它通过将数值更改为字符而产生了一个新问题.
sprintf() solves the problem with rounding, but it creates a new problem by changing the numeric value to a character.
谁能告诉我如何让 r 用数字输出给我 5/26*100 = 19.230769?
Can anyone show me how to get r to give me 5/26*100 = 19.230769 with a numeric output?
谢谢,
画画
推荐答案
问题是默认情况下,R 只会打印出 7 位数字.请参阅帮助页面 ?getOption
并搜索digits".
The problem is that by default, R will only print out 7 digits. See the help page ?getOption
and search for "digits".
您可以通过更改设置来更改此设置以允许更多数字.
You can change this by changing the setting to allow for more digits.
options(digits=13)
round(5/26*100,digits=6)
[1] 19.230769
round(5/26*100,digits=7)
[1] 19.2307692
round(5/26*100,digits=8)
[1] 19.23076923
这篇关于如何告诉 R 正确舍入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!