R:只在小数点后两位以上四舍五入

R: Rounding only if there are more than two decimal places

我希望将一组值四舍五入为最接近的整数,但前提是该数字有两位或更多位小数。否则,我想保持数字不变。

可以使用 gsubfn、正则表达式和多种类型转换来完成,但是有更优雅的方法吗?

library(gsubfn)

y <- c(210.61233,212.41, 213.2, 214)

y <- as.character(y)
as.numeric(gsubfn("(\d+\.\d{2,})", ~ round(as.numeric(x), 0) ,  y))
#211.0 212.0 213.2 214.0

一种可能是这样的:

y <- c(210.61233,212.41, 213.2, 214)

ifelse(y == round(y, 1), y, round(y))
[1] 211.0 212.0 213.2 214.0

首先检查数字四舍五入到一位数后是否发生变化。如果不是你保留它,否则你将它四舍五入到最接近的整数。

这可以说过于复杂了,但可以编写一个简单的函数如下:

y <- c(210.61233,212.41, 213.2, 214)


round_if<-function(my_vec,min_length){

my_pattern<-paste0("\.(?=\d{",min_length,",})")

to_replace<-grep(my_pattern,my_vec,perl=TRUE)

    my_vec[to_replace] <- round(Filter(function(x)grep(my_pattern,
                                   x,perl = TRUE),my_vec),0)
    my_vec

  }

在上面进行测试:

  round_if(y,2)
#[1] 211.0 212.0 213.2 214.0