我有一个数字,例如 10
。我想使用类似这样的方法将这个数字分成 5 个整数:
foo <- function(x, n) rep(x/n, n)
foo(10, 5)
[1] 2 2 2 2 2
这一直有效,直到 x
不是 n
的倍数:
foo(10, 3)
[1] 3.333333 3.333333 3.333333
在这种情况下,我想要这样的输出。
[1] 3 4 3 # the order doesn't matter.
每个整数之间的差异必须最小。所以这个结果是不允许的:
[1] 2 5 3
到目前为止我正在使用这个函数,但不确定这是否总是正确的:
foo <- function(x, n){
res <- rep(x/n, n)
res <- floor(res) # rounding
Diff <- x-sum(res) # Difference of the sum to the input
gr <- sample(1:n, Diff) # select by chance as many values as `Diff` is
res[gr] <- res[gr]+1 # plus one
res
}
最佳答案
您的功能应该可以工作,但每次都会给出不同的答案。此外,您可能想为此使用欧几里德除法,这就是您试图用 floor
和 Diff
来模仿的东西。在 R 中,你用 %/%
得到商,用 %%
得到余数
所以一个简单的解决方案可能是
foo <- function(x,n)
{
res=numeric(n)
a=x%/%n # the quotient
b=x%%n # the remainder
res[1:n]=a # fill with the quotient
if(b>0){
for(i in 1:b)
res[n-i+1]=res[n-i+1]+1 # add as many time a one in a cell as needed by the remainder
}
return(res)
}
关于r - 函数将 n 个整数除以 app.大小相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41997162/