根据小数位数四舍五入

Round depending on number of decimal places

我想要什么

我想根据实际小数位对大型数据集的所有数值进行四舍五入。

例如对于下面的 df ,我想将所有数字四舍五入,小数点后一位为整数,小数点后两位为小数点后一位。

更新 在原来的post中,我使用了iris作为数据集。由于iris确实只有一位小数,所以我添加了一个新的数据集:

   df <- tibble(one=round(runif(100,0,10), 1),
                 two=round(runif(100,0,10), 2),
                 characters=rep("thanks",100))

您可以只计算点后的数字并四舍五入到该值-1,即

x <- c(4.5, 2.12, 3, 5.245)
i1 <- nchar(sub('.*\.', '', x))

round(x, (i1-1))
#[1] 4.00 2.10 3.00 5.25

数据:

 v1 <- c(1.1, 1.2, 2.91, 5.9)

向量的解决方案:

这里的关键是使用grepl通过正则表达式识别带2位小数的数字;要使正则表达式工作,需要使用 as.character 将数据转换为字符。然后你可以简单地设置一个 ifelse 子句来确定如果条件评估为 TRUE,round 到 1 位小数,否则四舍五入到 0 位小数:

ifelse(grepl(".\d{2}$", as.character(v1)), round(v1,1), round(v1,0))

结果:

[1] 1.0 1.0 2.9 6.0

数据框的解决方案:

同样的原理可以应用于一次转换数据帧中的多个向量:

dt <- data.frame(
  v1 = c(1.11, 2.2, 3.9, 5.55),
  v2 = c(6.99, 7.07, 8.5, 9.01))

上面草拟的解决方案只需要成为 apply 语句中函数的一部分:

apply(dt, 2, function(x) ifelse(grepl(".\d{2}$", as.character(x)), round(x,1), round(x,0)))
      v1  v2
[1,] 1.1 7.0
[2,] 2.0 7.1
[3,] 4.0 8.0
[4,] 5.5 9.0