【问题标题】:How to extract numeric part with "e" from a string如何从字符串中提取带有“e”的数字部分
【发布时间】:2019-12-04 07:49:18
【问题描述】:

我有一个类似“reflectance_scales=5.011129178e-05”的字符串。 我想以数字形式提取“5.011129178e-05”部分。

我试过了:

gsub("[^0-9.]", "",  "reflectance_scales=5.011129178e-05")

但它只提取 5.011129178 而不是 e-05。

【问题讨论】:

  • 数字是否始终采用科学格式?
  • 您也可以使用split()= 作为分隔符。
  • @stud3nt 我要的是一般情况而不是这个特定的情况。 split() 不适用于每种情况。

标签: r regex string


【解决方案1】:

我们可以使用sub提取数字并使用eval(parse将其转换为数字。

eval(parse(text = sub(".*?(\\d.*)", "\\1",  "reflectance_scales=5.011129178e-05")))
#[1] 0.000050111

如果您没有表示数字的科学格式,这也应该有效。

eval(parse(text = sub(".*?(\\d.*)", "\\1",  "reflectance_scales=5.0123")))
#[1] 5.0123

您也可以在不使用eval parse 的情况下使用相同的代码,也可以将其包装在as.numeric

as.numeric(sub(".*?(\\d.*)", "\\1",  "reflectance_scales=5.011129178e-05"))
#[1] 0.000050111

【讨论】:

    【解决方案2】:

    你可以试试

    r <- gsub("\\w.*?=", "", "reflectance_scales=5.011129178e-05")
    

    给了

    > r
    [1] "5.011129178e-05"
    

    如果你想要它作为数字类型,那么使用as.numeric(r)

    【讨论】:

      【解决方案3】:

      比@RonakShah 的回答更简单,并使用@llllllIIIIll 的想法,您可以分两步完成(无需正则表达式):

      word = "reflectance_scales=5.011129178e-05"
      numb = as.numeric(unlist(strsplit(word,"=")))
      numb = numb[!is.na(numb)]
      

      然后得到:

      > str(numb)
       num 5.01e-05
      

      【讨论】:

        【解决方案4】:

        基础 R 解决方案:

        # Solution 1, string split, unlist, coerce to numeric, subset out NAs, coerce to numeric, 
        # format with scientific notation (type coercion to string): 
        
        format(as.numeric(na.omit(as.numeric(unlist(strsplit(X, "="))))), scientific = TRUE)
        
        # Solution 2, substitution of alphabetic characters coercion to numeric
        # format with scientific notation (type coercion to string)
        
        format(as.numeric(gsub("[^0-9]+", "", X)), scientific = TRUE)
        
        # Solution 3, string split, digit extraction:
        
        grep("\\d+", unlist(strsplit(X, "=")), value = TRUE)
        

        数据:

        X <- as.character("reflectance_scales=5.011129178e-05")
        

        基准测试:

        # Install pacakges if they are not already installed: 
        
        necessary_packages <- c("bench")
        
        # Create a vector containing the names of any packages needing installation: 
        
        new_packages <- necessary_packages[!(necessary_packages %in% installed.packages()[,"Package"])]
        
        # If the vector has more than 0 values, install the new pacakges
        # (and their) associated dependencies: 
        
        if(length(new_packages) > 0){
        
          install.packages(new_packages, dependencies = TRUE)
        
        }
        
        # Initialise the packages in the session: 
        
        lapply(necessary_packages, require, character.only = TRUE)
        
        # Benchmark the solutions: 
        
        function_performance <- bench::mark(
        
          # Solution 1, string split, unlist, coerce to numeric, subset out NAs, coerce to numeric, 
          # format with scientific notation (type coercion to string): 
        
          format(as.numeric(na.omit(as.numeric(unlist(strsplit(X, "="))))), scientific = TRUE),
        
          # Solution 2, substitution of alphabetic characters coercion to numeric
          # format with scientific notation (type coercion to string)
        
          format(as.numeric(gsub("[^0-9]+", "", X)), scientific = TRUE),
        
          # Solution 3, string split, digit extraction:
        
          grep("\\d+", unlist(strsplit(X, "=")), value = TRUE), 
        
        check = FALSE)
        
        # Check the function performance: 
        
        View(function_performance)
        

        【讨论】:

          【解决方案5】:

          或者只是像列表定义一样解析它:

          x <- "reflectance_scales=5.011129178e-05"
          eval(str2lang(paste0("list(",x,")")))[[1]]
          #> [1] 5.011129e-05
          

          reprex package (v0.3.0) 于 2019 年 12 月 4 日创建

          与 Ronak 的回答相比,这非常有效:

          x <- "reflectance_scales=5.011129178e-05"
          bench::mark(
          mm = eval(str2lang(paste0("list(",x,")")))[[1]],
          ronak = eval(parse(text = sub(".*?(\\d.*)", "\\1",  x)))
          )
          #> # A tibble: 2 x 6
          #>   expression      min   median `itr/sec` mem_alloc `gc/sec`
          #>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
          #> 1 mm            5.9us    7.8us    72889.    2.08KB     7.29
          #> 2 ronak        29.6us   31.4us    24103.      280B     9.65
          

          reprex package (v0.3.0) 于 2019 年 12 月 4 日创建

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2016-01-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多