R:仅在小数点后两位以上时才四舍五入

时间:2019-06-07 14:53:01

标签: r rounding

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

可以使用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

2 个答案:

答案 0 :(得分:4)

一种可能性是

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

首先,您需要检查数字是否四舍五入为整数。如果不保留,则将其舍入到最接近的整数。

答案 1 :(得分:2)

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

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
相关问题