When calculating a proportion (0 < x < 1) I am looking to convert that result x into it's nearest 1/r form, so that for example for
x = 0.30 is converted into 1/3
whereas for
x = 0.29 is converted into 1/4
I have been trying different ideas using round() and fractions() from MASS with little success.
What would be your most simple solution in R that could make this work?
To round to nearest one, ten, hundred, thousand and so on: if the rounding digit is 0, 1, 2, 3, or 4, change all digits to the right of it to zeroes. if the rounding digit is 5, 6, 7, 8, or 9, add one to the rounding digit and change all digits to the right of it to zeroes.
When computing sample sizes needed to estimate a population mean or estimate a population proportion, if there is any non-zero amount to the right of the decimal point, you must round the result UP TO THE NEXT INTEGER.
Note that for rounding off a 5, the IEEE standard is used, ``go to the even digit''. Therefore round(0.5) is 0 and round(-1.5) is -2 . signif rounds the values in its first argument to the specified number of significant digits.
The following might do what you want, returning either the ceiling or the floor of the reciprocal (whichever gives a better result):
f <- function(x) ifelse(abs(1/floor(1/x) - x) < abs(1/ceiling(1/x) - x),floor(1/x),ceiling(1/x))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With