在保留特定间隔的总和的同时舍入值

时间:2018-10-31 16:06:35

标签: r math rounding

我要舍入一个值向量,同时保留总和并考虑一个间隔数。

假设我有一个向量:

vector <- c(0.2, 1.8, 40.4, 10.6, 0.5, 1.5)

现在,我想在保留数字55的总和的同时四舍五入。此函数的作用是:

smart.round <- function(x) {
   y <- floor(x)
   indices <- tail(order(x-y), round(sum(x)) - sum(y))
   y[indices] <- y[indices] + 1
   y
}
  

smart.round(vector)
  [1] 0 2 40 11 0 2

但是我还要考虑用户定义的间隔。假设5。此函数仅执行以下操作:

mround <- function(x,base){ 
   base*round(x/base) 
}  
  

mround(vector,5)
  [1] 0 0 40 10 0 0

现在,我想结合两个功能。但是我不知道怎么做。基本上我希望输出为:

vector <- c(0.2, 1.8, 40.4, 10.6, 0.5, 1.5) 
  

combined.round(vector,5)
  [1] 0 5 40 10 0 0

(因为1.8最接近5,并且至少一个值需要四舍五入以保留55的总和) 总和为55,并且每个数字在所需输出中的间隔为5。

任何帮助或建议,我们将不胜感激!

0 个答案:

没有答案
相关问题