在 R 中将值四舍五入到最接近的十位或百位?

Qui*_*tic 2 r rounding

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

Student   Computed Score
1         71.00   
2         55.3489
3         2000.11111
4         1689.66
Run Code Online (Sandbox Code Playgroud)

我想将它们四舍五入到最接近的“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,这没有帮助)。

Rui*_*das 5

也许下面会做到。

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)
Run Code Online (Sandbox Code Playgroud)

编辑。

在用户 ORStudent发表评论后,我编写了一个新函数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
Run Code Online (Sandbox Code Playgroud)