我有一个十进制数向量,范围从 -10 到 10,具有不同的小数深度。
我想输出此向量的舍入版本,以便所有数字都在最后显示非 0 小数的小数级别进行舍入(例如 0.0040 在 0.1000 之后显示非 0 小数,舍入应为 3 )。我的目标是在舍入向量后始终输出非 0 值。
在以下示例中,显示第一个非 0 值的十进制数为 0.000100,因此所有数字都应四舍五入为 4。值
1.000002
不应四舍五入为 6,因为它已经与 0 不同。
### Initiating vector of values, only 0s and 1s should be displayed because the deepest decimal level is 4. 2s should not be displayed
tmpVector <- c(0.111120, -11.011102, 0.001100, 0.000100, 1.000002, -0.101022)
### Correct rounding
round(tmpVector, 4)
[1] 0.1111 -11.0111 0.0011 0.0001 1.0000 -0.1010
我想找到一种自动方法,可以用
round(tmpVector, 4)
替换 round(tmpVector, deepestLevel)
。
找不到其他版本的
round()
函数来解决这个问题。
好的,所以我们可以像这样提取最低指数:
tmpVector |>
abs() |> # some values are negative - we don't care
log10() |> # log gives us the exponent
min() |> # find the smallest
floor() |> # make an integer
abs() # stop it being negative
# gives:
4
然后将其合并到
round()
中:
round(tmpVector, tmpVector |> abs() |> log10() |> min() |> floor() |> abs())
[1] 0.1111 -11.0111 0.0011 0.0001 1.0000 -0.1010
我会提供一种基于性格的方法:
library(stringr)
tmpVector <- as.character(tmpVector)
str_extract(tmpVector, pattern = "\\A[\\-]*[0-9]*[\\.]+[0-9][1-9]*") |> as.numeric()
[1] 0.11112 -11.01110 0.00000 0.00000 1.00000 -0.10000
解释:我们找到并提取
-
符号(如果存在)、小数分隔符 .
之前的数字、小数分隔符之后的一位(任意,0-9)数字以及后面不等于 0 的尽可能多的数字。