r - 函数将 n 个整数除以 app.大小相同

标签 r integer division

我有一个数字,例如 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   
  }

最佳答案

您的功能应该可以工作,但每次都会给出不同的答案。此外,您可能想为此使用欧几里德除法,这就是您试图用 floorDiff 来模仿的东西。在 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/

相关文章:

r - 使用ggplot facet_grid在不同条件下相同变量的散点图?

r - 使用 R Shiny 一键下载多个 csv 文件(下载处理程序)

Java:两个有序整数序列的交集

python - 为什么 Go 和 Python 在除大数时返回不同的结果?

r - 如何用EOF解决fread txt的问题?

r - 我无法在 rstudio 中安装 rvest 包

c - C语言中如何确定无符号长整型的范围?

C++ 线程安全整数

Python-将数据框除以数字列表,包括零

OpenGL 4.4 管道 - 裁剪前的透视划分?