R中的最近几十或数百的圆值?

时间:2017-09-09 22:44:38

标签: r rounding

我的数据框中有超过10,000个测试分数计算错误。它们看起来像这样:

Student   Computed Score
1         71.00   
2         55.3489
3         2000.11111
4         1689.66

我想将它们四舍五入到最接近的'10'(变量1:71 = 70,1689.66 = 1690),并且最接近'100'(变量2:71 = 100,1689.66 = 1700)。因为原始值是以10点增量和100点分界计算的。我试过了:

df$Var1<-round(df$Computed_Score, 2)
但它将小数位四舍五入为2个值(2000.11111变为2000.11,这没有帮助)。

1 个答案:

答案 0 :(得分:4)

以下可能会这样做。

x <- scan(text = "
71.00   
55.3489
2000.11111
1689.66")
x

round_to <- function(x, to = 10) round(x/to)*to

round_to(x)
round_to(x, 100)

修改。

用户ORStudent comment后我写了一个新函数roundup_to

roundup_to <- function(x, to = 10, up = FALSE){
  if(up) round(.Machine$double.eps^0.5 + x/to)*to else round(x/to)*to
}

roundup_to(c(150, 116350), to = 100)
# [1]    200 116400

roundup_to(c(150, 116350), to = 100, up = TRUE)
# [1]    200 116400

roundup_to(c(50, 116250), to = 100)
#[1]      0 116200

roundup_to(c(50, 116250), to = 100, up = TRUE)
#[1]    100 116300