【问题标题】:extract varying length number from text strings from a vector in R从R中的向量中的文本字符串中提取不同长度的数字
【发布时间】:2019-08-23 18:46:48
【问题描述】:

我需要从文本中提取一个数字如下:

A<- c( '\n      0 requests\n        in 2008\n    ', '\n      1,320 requests\n        in 2008\n    ', '\n      64 requests\n        in 2008\n    ')
B<- c('John','KL', 'LK')

我想从上面的文本中获取打开的请求数。在这种情况下,我需要获取数字

A       C
John    0
KL      1,320
LK      64

关于如何提取这个可变长度子字符串的任何建议?非常感谢

【问题讨论】:

    标签: r dplyr tidyr stringr


    【解决方案1】:

    你可以这样做:

    library(stringr)
    y <- do.call(rbind, lapply(A, function(x){str_extract_all(x,"\\(?[0-9,.]+\\)?")[[1]]}))
    setNames(as.data.frame(cbind(B,y[,1])), c("A", "C"))
    
    
    > setNames(as.data.frame(cbind(B,y[,1])), c("A", "C"))
         A     C
    1 John     0
    2   KL 1,320
    3   LK    64
    

    【讨论】:

      【解决方案2】:

      使用str_extract 和正向预测

      library(dplyr)
      #\\d*\\,?\\d* (?=requests) 0+ digits followed by 0 or 1 , followed by 0+ digit 
      #This pattern must followed by the word requests
      df %>% mutate(C=stringr::str_extract(A,'\\d*\\,?\\d* (?=requests)'))
      
                                                A    B      C
      1     \n      0 requests\n        in 2008\n     John     0 
      2 \n      1,320 requests\n        in 2008\n       KL 1,320 
      3    \n      64 requests\n        in 2008\n       LK    64 
      

      注意:我假设您最多有一个 ,。如果有多个,,请使用@Hayden 的建议stringr::str_extract(A,'(\\d*\\,?)*\\d* (?=requests)')

      【讨论】:

      • 如果您有任何超过 6 位的数字,您可以将捕获组添加到模式中,例如 '(\\d*\\,?)*\\d* (?=request)'
      【解决方案3】:
      transform(read.table(text=gsub("\\n?\\s+",";",A),sep=";",fill = T),V1=B)[1:2]
      
          V1    V2
      1 John     0
      2   KL 1,320
      3   LK    64
      

      【讨论】:

        猜你喜欢
        • 2020-12-31
        • 1970-01-01
        • 2016-10-02
        • 1970-01-01
        • 2016-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        相关资源
        最近更新 更多