我的数字差异很大。从很小到很大。我想将它们全部取整,但看不到适合我的解决方案。
通常,人们会四舍五入到小数位数。只需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)
但他们不能解决我的问题。
P.S。 抱歉造成混乱。 我想将小数四舍五入到最接近的小数点(不确定我是否用英语正确解释了,抱歉)。
因此它应该是一个自定义函数。我将用一些小数点(从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
答案 0 :(得分:2)
不确定您要问什么。也许这行得通-还是让您更接近?
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