【问题标题】:R: Rounding only if there are more than two decimal placesR:仅当小数点超过两位时才四舍五入
【发布时间】:2019-10-23 02:23:19
【问题描述】:

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

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

【问题讨论】:

  • 你可以测试是否10*x == floor(10*x)。如果不是,x 有多个小数/
  • 您能解释一下为什么它很重要吗?我猜这些值是要显示给用户的,但是显示这些小数有那么尴尬吗?
  • 这些值来自两个不同的来源,其中一个是最终用户习惯的。

标签: r rounding


【解决方案1】:

一种可能性是:

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

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

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多