【问题标题】:R replace strings not like two strings?R替换字符串不像两个字符串?
【发布时间】:2021-04-16 16:11:11
【问题描述】:

我正在使用 R 中的 sub 函数来替换任何不以 M 开头的字符串或不以 T814 开头的字符串。我有下面的代码成功地保留了任何以 M 开头的字符串,但它没有保留以 T814 开头的字符串。

attempt2$dx3 <- sub('^[^M].*| ^[^T814].*', "", attempt2$dx3)

有什么办法可以调整代码只保留我感兴趣的字符串?

这是我所拥有的一个例子:

attempt2 <- data.frame(dx2 = c("M1234", "T8142", "M745", "T8149", "R234"),
                   dx3 = c("M356", "T1142", "M745", "T8146", "G234"))

以及我想要的:

attempt2 <- data.frame(dx2 = c("M1234", "T8142", "M745", "T8149", ""),
                   dx3 = c("M356", "", "M745", "T8146", ""))

【问题讨论】:

  • 对于正则表达式中的“不是(多个字符串)”,我相信您的选择是(a)使用否定前瞻as shown here,或者(b)匹配多字符串然后否定。
  • 你真的不想要attempt2$dx3 &lt;- sub('(?s)^(?!M|T814).*', "", attempt2$dx3, perl=TRUE),是吗?

标签: r regex grepl


【解决方案1】:

由于您正在替换整个字符串,因此您可以检测匹配项,然后替换所有不匹配项:

attempt2$dx3[!grepl("^(M|T184)", attempt2$dx3)] <- ""

我认为另一种选择是消极的前瞻性,而 Wiktor 的评论可能是正确的。

【讨论】:

    【解决方案2】:

    使用str_detect

    library(stringr)
    library(dplyr)
    attempt2 %>% 
       mutate(dx3 = replace(dx3, !str_detect(dx3, "^(M|T8146)"), ""))
    

    【讨论】:

      【解决方案3】:

      有一个方便的库:

      library(inops)
      attempt2 %out~% c("^M", "^T814") <- ""
      

      这里%out~% 匹配所有与右侧指定的正则表达式不匹配的元素。然后,您可以在行尾为该表达式分配一个替换值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 2022-12-15
        相关资源
        最近更新 更多