问题
I have a number, for instance 10
. I want to split this number in 5 integers using something like this:
foo <- function(x, n) rep(x/n, n)
foo(10, 5)
[1] 2 2 2 2 2
This works until x
is not a mutliple of n
:
foo(10, 3)
[1] 3.333333 3.333333 3.333333
In this case I woud like an output like.
[1] 3 4 3 # the order doesn't matter.
The difference between each integer have to be minimal. So this result is not allowed:
[1] 2 5 3
So far I'm using this function, but not sure whether this is always correct:
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
}
回答1:
Your function should work but will give a different answer every time. Also you probably want to use the Euclidian division for that, which is what you a trying to mimcik with floor
and Diff
. In R you get the quotient with %/%
and the remainder with %%
So a simple solution could be
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)
}
回答2:
This I thought was an intriguing question. I figured out that the remainder indicates the number of (quotient+1) numbers you have. For example:
17/7 = 2 + 3/7 --> So you need (7-3) x 2 and 3 x (2+1)
19/7 = 2 + 5/7 --> So you need (7-5) x 2 and 5 x (2+1)
Leading to a more elegant solution:
foo <- function(x,n){
a = x%/%n # the quotient
b = x%%n # the remainder
return(c(rep(a,n-b),rep(a+1,b)))
}
回答3:
This should work:
foo <- function(x, n) rep(x%/%n, n) + sample(c(rep(1, x %% n), rep(0, n - x %% n)), n)
foo(10, 5)
[#1] 2 2 2 2 2
foo(10, 3)
#[1] 3 3 4
来源:https://stackoverflow.com/questions/41997162/function-dividing-a-number-in-n-integer-with-app-same-size