【问题标题】:round all float numbers in a string将字符串中的所有浮点数舍入
【发布时间】:2016-07-05 12:54:36
【问题描述】:

我试图用四舍五入到小数点后 2 位的相同数字替换字符串中的所有浮点数。例如"Hello23.898445World1.12212" 应该变成"Hello23.90World1.12"

我可以通过gregexpr("[[:digit:]]+\\.*[[:digit:]]*", str)[[1]] 找到数字的位置,但不知道如何用圆角原件替换它们。

【问题讨论】:

    标签: r replace


    【解决方案1】:

    我们可以使用gsubfn

    library(gsubfn)
    gsubfn("([0-9.]+)", ~format(round(as.numeric(x), 2), nsmall=2), str1)
    #[1] "Hello23.90World1.12"
    

    数据

    str1 <- "Hello23.898445World1.12212"
    

    【讨论】:

      【解决方案2】:

      或者使用stringr:

      library(stringr)
      x <- "Hello23.898445World1.12212"
      
      r1 <- round(as.numeric(str_extract_all(x, "-*\\d+\\.*\\d*")[[1]]),2)
      # [1] 23.90  1.12
      r2 <- strsplit(gsub("\\d", "", x),"\\.")[[1]]
      # [1] "Hello" "World"
      paste0(r2, format(r1, digits = 3, trim=T), collapse = "")
      
      # [1] "Hello23.90World1.12"
      

      【讨论】:

        【解决方案3】:

        不使用包进行字符串操作的解决方案:

        也归功于@akrun format(., nsmall=2) 是这个解决方案的诀窍。

        输入字符串

        stringi <- "Hello23.898445World1.12212"
        

        设置小数位数

        dp <- 2 #decimal places
        

        计算

        strsplit(x = stringi,split = "(?<=[^0-9.])(?=\\d)|(?<=\\d)(?=[^0-9.])",perl=T) %>%
            unlist %>% 
            lapply(function(x){if(!is.na(as.numeric(x)))x<-round(as.numeric(x),dp)%>%format(nsmall=dp);x}) %>%
            paste(collapse="")
        

        结果:

        #[1] "Hello23.90World1.12"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-05
          • 2018-12-08
          • 2021-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多