【问题标题】:R extract unit of measure and attached number from string given list of units of measuresR从给定的度量单位列表中提取度量单位和附加编号
【发布时间】:2018-02-23 05:17:10
【问题描述】:

我正在使用 R 并且我有两个字符向量:

measures <- c('cm', 'mm', 'ml')
strings <- c('hgtrdhg cm12 mhjgf','asdfsf 12mm jhgjhg','adadf 45ml','ml89 jygjgh', 'cm 59 gfhgfd')

我必须为每个字符串提取度量单位和相关的数字,例如:

cm12、12mm、45ml、ml89、cm59 (原来最后一个字符串cm到59之间有一个空格)

数字可以在度量单位之前或之后。

【问题讨论】:

    标签: r substring


    【解决方案1】:

    我们可以遍历“度量”并提取元素

    library(dplyr)
    library(stringr)
    library(purrr)
    measures %>%
           map(~ str_extract(strings, paste0("\\d*", .x, "\\s*\\d*"))) %>%
        do.call(coalesce, .) %>%
        str_replace_all(" ", "")
    #[1] "cm12" "12mm" "45ml" "ml89" "cm59"
    

    或者,如果我们想一次使用所有“措施”,那么 paste collapse| 一起使用

    pat <- paste0("(", paste("\\d*", measures, "\\s*\\d*", sep="", collapse="|"), ")")
    str_replace_all(str_extract(strings, pat), " ", "")
    #[1] "cm12" "12mm" "45ml" "ml89" "cm59"
    

    【讨论】:

      【解决方案2】:

      使用基础 r:

      m=paste0(".*?(\\d+\\s*(",m<-paste0(measures,collapse = "|"),")|(",m,")\\s*\\d+).*")
      > sub(m,"\\1",strings)
      [1] "cm12"  "12mm"  "45ml"  "ml89"  "cm 59"
      
      sub(".*?(\\d+\\s*(cm|mm|ml)|(cm|mm|ml)\\s*\\d+).*","\\1",strings)
         [1] "cm12"  "12mm"  "45ml"  "ml89"  "cm 59"
      

      【讨论】:

        猜你喜欢
        • 2021-11-29
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 2015-10-03
        • 2011-02-05
        • 2011-09-22
        • 1970-01-01
        • 2012-07-09
        相关资源
        最近更新 更多