Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 函数用app将一个数除以n整数。同样大小_R_Integer_Division - Fatal编程技术网

R 函数用app将一个数除以n整数。同样大小

R 函数用app将一个数除以n整数。同样大小,r,integer,division,R,Integer,Division,我有一个数字,例如10。我想用如下方法将这个数字拆分为5个整数: foo <- function(x, n) rep(x/n, n) foo(10, 5) [1] 2 2 2 2 2 在这种情况下,我希望输出像 [1] 3 4 3 # the order doesn't matter. 每个整数之间的差异必须最小。所以这个结果是不允许的: [1] 2 5 3 到目前为止,我正在使用此函数,但不确定这是否总是正确的: foo <- function(x, n){

我有一个数字,例如
10
。我想用如下方法将这个数字拆分为5个整数:

foo <- function(x, n) rep(x/n, n)
foo(10, 5)
[1] 2 2 2 2 2
在这种情况下,我希望输出像

[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   
  }

foo您的函数应该可以工作,但每次都会给出不同的答案。此外,您可能希望使用欧几里得除法,这是您试图用
地板
差异
模拟的。在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)
}
foo(0){
(1:b中的i)
res[n-i+1]=res[n-i+1]+1#根据余数的需要在单元格中添加任意多的时间
}
返回(res)
}

我认为这是一个有趣的问题。我发现余数表示你拥有的(商+1)个数。例如:

17/7=2+3/7-->所以需要(7-3)x2和3x(2+1)

19/7=2+5/7-->所以需要(7-5)x2和5x(2+1)

带来更优雅的解决方案:

  foo <- function(x,n){
     a = x%/%n # the quotient
     b = x%%n  # the remainder
     return(c(rep(a,n-b),rep(a+1,b)))
}
foo这应该可以:

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

欧几里得除法是一个很好的观点。谢谢我故意选择了“按cance方法”。
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