如何将一个数字转换为R中另一个数字的第一个整除数
How to convert a number to the first divisible of another one in R
我想将任何数字除以 6
仍然有一个整数。那么如何让 R
将数字转换为最接近的可整除数字。
例如 607
在这种情况下应转换为 606
。
这是三种方法
foo_Gregor = function(N, n){
return(round(N / n) * n)
}
foo_HubertL = function(N, n){
return(n*((N+n/2) %/% n))
}
foo_db = function(N, n){
t1 = N %% n
if (t1 < n/2){
return(N - t1)
} else {
return(N + n - t1)
}
}
var_db = sapply(1:10000, function(i) foo_db(N = i, n = 6))
var_Gregor = sapply(1:10000, function(i) foo_db(N = i, n = 6))
var_HubertL = sapply(1:10000, function(i) foo_db(N = i, n = 6))
identical(var_db, var_Gregor)
#[1] TRUE
identical(var_HubertL, var_Gregor)
#[1] TRUE
foo_Gregor
可能是最好的,因为它简单并且可以用 floor
或 ceiling
修改它
我想将任何数字除以 6
仍然有一个整数。那么如何让 R
将数字转换为最接近的可整除数字。
例如 607
在这种情况下应转换为 606
。
这是三种方法
foo_Gregor = function(N, n){
return(round(N / n) * n)
}
foo_HubertL = function(N, n){
return(n*((N+n/2) %/% n))
}
foo_db = function(N, n){
t1 = N %% n
if (t1 < n/2){
return(N - t1)
} else {
return(N + n - t1)
}
}
var_db = sapply(1:10000, function(i) foo_db(N = i, n = 6))
var_Gregor = sapply(1:10000, function(i) foo_db(N = i, n = 6))
var_HubertL = sapply(1:10000, function(i) foo_db(N = i, n = 6))
identical(var_db, var_Gregor)
#[1] TRUE
identical(var_HubertL, var_Gregor)
#[1] TRUE
foo_Gregor
可能是最好的,因为它简单并且可以用 floor
或 ceiling