问题
How can I tell R to round correctly?
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
gives me:
[1] 19.23077
Let's try to use round(), first setting the digits to 4:
x <- round(5/26*100,digits=4)
x
gives:
[1] 19.2308
Next, let's set the digits to 5:
x <- round(5/26*100,digits=5)
x
gives:
[1] 19.23077
Now, let's set the digits to 6:
x <- round(5/26*100,digits=6)
x
gives:
[1] 19.23077
Can anyone tell me how to fix this? Do you get the same results, or does your rstudio round correctly?
I have also tired signif()
x <- signif(5/26*100,digits=6)
x
gives us:
[1] 19.2308
increasing to 7 digits:
> x <- signif(5/26*100,digits=7)
> x
[1] 19.23077
Increasing to 8 digits:
> x <- signif(5/26*100,digits=8)
> x
[1] 19.23077
And we can use sprintf()
> x <- sprintf("%0.6f", (5/26*100))
> x
[1] "19.230769"
sprintf() solves the problem with rounding, but it creates a new problem by changing the numeric value to a character.
Can anyone show me how to get r to give me 5/26*100 = 19.230769 with a numeric output?
Thank you,
Drew
回答1:
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
回答2:
The round function does the calculation and return significant digits based on digits parameter assigned to round function. But the digits setting at global option controls what you see in command line output.
You can modify digits value using options or you can try to convert to as.character to see the desired output.
My current digits setting in options is 5 still below calculation works.
Example:
> as.character(round(5/26*100, 6))
[1] "19.230769"
> as.character(round(5/26*100, 7))
[1] "19.2307692"
来源:https://stackoverflow.com/questions/48361017/how-can-i-tell-r-to-round-correctly