我的数字差异很大。从很小到很大。我想将它们全部舍入,但没有找到适合我的解决方案。
通常人们会四舍五入到一定的小数位数。简单地 round(x, 2)
或其他。
我的情况有所不同。
例如,我有非常不同的数字。小于 1 且有多个零的数字是我最大的挑战,因为我不希望它们四舍五入为零。
x <- c(100.56, 100.132554444123, 10044400000.2523324,
1.2343454555424, 0.04454443, 0.0000000000000000000000543)
lapply(x, signif)
它给了我
[[1]]
[1] 100.56
[[2]]
[1] 100.133
[[3]]
[1] 10044400000
[[4]]
[1] 1.23435
[[5]]
[1] 0.0445444
[[6]]
[1] 0.0000000000000000000000543
这几乎就是我所需要的。但我想将数字限制在 1 以下,并保留一些小数。例如,将其四舍五入为最接近的有意义的小数(第一个非零数字)。
我还尝试了其他一些选项,例如
prettyNum(x)
formatC(x)
但他们没有解决我的问题。
附注 抱歉造成困惑。 我想将小数字四舍五入到最接近的小数(不确定我是否用英语正确解释,抱歉)。
所以它应该是一个自定义函数。我会将大数四舍五入到一定的小数位(从 0 到 3)。像这样
x <- c(100.56, 100.132554444123, 100444.2523324, 1.2343454555424, 0.04454443, 0.0000000000000000000000543)
rounded_value <- function(value) {
if (is.na(value)) return (NA)
if (value >= 100) value <- round(value,2)
if (value >= 1000) value <- round(value,0)
if (value >= 1000000) value <- round(value,3)
return (value)
}
lapply(x, rounded_value)
[[1]]
[1] 100.56
[[2]]
[1] 100.13
[[3]]
[1] 100444
[[4]]
[1] 1.234345
[[5]]
[1] 0.04454443
[[6]]
[1] 0.0000000000000000000000543
我的问题是最后两个值 - 0.04454443、0.0000000000000000000000543。 我想将值单独舍入到 1 以下。例如,分为 0.04 和 0.00000000000000000000006。试图找到一个可以帮助我做到这一点的函数。
已更新。谢谢大家。我正在尝试以更直观的方式重写这个函数。抱歉,如果我最初的问题与您在这里看到的不完全一样。
rounded_value <- function(value)
{
if (is.na(value)) return (NA)
decimals <- 1
value_out <- value
while ( (value_out<-round(value,(decimals+1))) == 0 & decimals < 10) {
decimals <- decimals + 1 }
if (value_out > 100) value_out <- round(value_out,1)
if (value_out > 1000) value_out <- round(value_out,0)
value_out <- as.numeric(value_out)
return (value_out)
}
更新 3。我现在最好的猜测是
x <- c(100.56, 100.132554444123, 100444.2523324, 1.2343454555424, 0.04454443,
0.00543)
rounded_value <- function(value) {
# if (is.na(value)) return (NA)
if (value >= 100) value <- round(value,2)
if (value >= 1000) value <- round(value,0)
if (value >= 1000000) value <- round(value,3)
while (value <= 1) value <- signif(x, 10)
return (value)
}
rounded_value(x)
它给了我
[1] 100.56 100.13 100444.25 1.23 0.04 0.01
最佳答案
不太清楚你在问什么。也许这会起作用 - 或者让你更接近?
R> x <- c(100.56, 100.132554444123, 10044400000.2523324,
+ 1.2343454555424, 0.04454443, 0.0000000000000000000000543)
R> ifelse(abs(x)>1, round(x), signif(x, digits=1))
[1] 1.01000e+02 1.00000e+02 1.00444e+10 1.00000e+00 4.00000e-02 5.00000e-23
关于将所有低于 1 的数字四舍五入到零后的第一个小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51699553/