【问题标题】:Regex string match words pattern正则表达式字符串匹配单词模式
【发布时间】:2021-05-23 22:26:35
【问题描述】:

我对抗生素有这种模式

atb <- c("acefa","ampicilin","fortum")

还有这个数据框

    DF1 <- structure(list(ID = 1:3, Text = c("Person 1 take acefa and ampicilin", "fortum and acefa are antibiotics", "Person 3 has no antibiotics but ampicilin")), class = "data.frame", row.names = c(NA, -3L))

DF1
    
    ID                                      Text
    1           Person 1 take acefa and ampicilin
    2            fortum and acefa are antibiotics
    3   Person 3 has no antibiotics but ampicilin

我想得到这个

DF1
        
    ID                                      Text        atb
    1           Person 1 take acefa and ampicilin      c("acefa","ampicilin")
    2            fortum and acefa are antibiotics      c("fortum","acefa")
    3   Person 3 has no antibiotics but ampicilin      ampicilin

我试过了

DF1%>%
mutate(atb = regmatches(Text, regexec(atb, Text)))

DF1%>%
mutate(atb =  str_extract_all(Text, atb)))

但它不起作用。

但是,它可以像这样与 grepl 一起使用

DF1%>%
    mutate(atb =  grepl(atb, Text))) 

我可以从模式中获取包含单词的列吗?

【问题讨论】:

    标签: r regex string grepl


    【解决方案1】:

    设置正则表达式并使用strapplyc:

    library(dplyr)
    library(gsubfn)
    
    result <- DF1 %>% 
      mutate(atb = strapplyc(Text, paste(atb, collapse = "|")))
    
    str(result$atb)
    

    给予:

    List of 3
     $ : chr [1:2] "acefa" "ampicilin"
     $ : chr [1:2] "fortum" "acefa"
     $ : chr "ampicilin"
    

    【讨论】:

      猜你喜欢
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 2014-07-09
      • 2016-12-03
      • 1970-01-01
      相关资源
      最近更新 更多