我特别需要在R中"转换"一个数字.例如,
"floor"操作表现为:
138 -> 100
1233 -> 1000
Run Code Online (Sandbox Code Playgroud)
"天花板"操作表现为:
138 -> 200
1233 -> 2000
Run Code Online (Sandbox Code Playgroud)
在R中有一种简单的方法可以实现这一点吗?谢谢
sgi*_*ibb 13
你可以分别提取指数:
floorEx <- function(x) {
ex <- 10^trunc(log10(x))
return(trunc(x/ex)*ex)
}
ceilingEx <- function(x) {
ex <- 10^trunc(log10(x))
return(ceiling(x/ex)*ex)
}
Run Code Online (Sandbox Code Playgroud)
例子:
floorEx(123)
# [1] 100
ceilingEx(123)
# [1] 200
ceilingEx(c(123, 1234, 12345))
# [1] 200 2000 20000
Run Code Online (Sandbox Code Playgroud)
编辑:
trunc代替floor和集成旧的ex函数(ex <- function(x)floor(log10(x)))来加速计算一点点floorR风向标:
## provided by @eddi
floorR <- function(x) {r <- signif(x, 1); r - (r > x) * 10^trunc(log10(x))}
library("microbenchmark")
x <- 123; microbenchmark(floorEx(x), floorR(x), signif(x), times=1e4)
# Unit: nanoseconds
# expr min lq median uq max neval
# floorEx(x) 2182 2414 2521 2683.0 704190 10000
# floorR(x) 2894 3150 3278 3505.5 22260 10000
# signif(x) 372 472 507 556.0 10963 10000
x <- 1:1000; microbenchmark(floorEx(x), floorR(x), signif(x), times=1e2)
# Unit: microseconds
# expr min lq median uq max neval
# floorEx(x) 100.560 101.2460 101.6945 115.6385 818.895 100
# floorR(x) 354.848 355.4705 356.0420 375.9210 1074.582 100
# signif(x) 114.608 115.2120 115.4695 119.1805 186.738 100
Run Code Online (Sandbox Code Playgroud)
它没有直接回答你的问题,但你也可以看看signif:
R> x <- 138
R> signif(x,1)
[1] 100
R> x <- 1712
R> signif(x,1)
[1] 2000
Run Code Online (Sandbox Code Playgroud)
另外一个选项:
floor2 <- function(x) {
mag <- 10^(nchar(round(x))-1)
(x %/% mag) * mag
}
ceil2 <- function(x) {
mag <- 10^(nchar(round(x))-1)
((x + mag) %/% mag) * mag
}
Run Code Online (Sandbox Code Playgroud)