R替换字符串不象两个字符串?
我使用R中的子函数替换任何不以M开头或不以T814开头的字符串。下面的代码成功地保留了任何以M开头的字符串,但没有保留以T814开头的字符串R替换字符串不象两个字符串?,r,regex,grepl,R,Regex,Grepl,我使用R中的子函数替换任何不以M开头或不以T814开头的字符串。下面的代码成功地保留了任何以M开头的字符串,但没有保留以T814开头的字符串 attempt2$dx3 <- sub('^[^M].*| ^[^T814].*', "", attempt2$dx3) attempt2$dx3由于您正在对整个字符串进行子串,因此可以检测匹配项,然后替换所有不匹配项: attempt2$dx3[!grepl("^(M|T184)", attempt2$dx
attempt2$dx3 <- sub('^[^M].*| ^[^T814].*', "", attempt2$dx3)
attempt2$dx3由于您正在对整个字符串进行子串,因此可以检测匹配项,然后替换所有不匹配项:
attempt2$dx3[!grepl("^(M|T184)", attempt2$dx3)] <- ""
attempt2$dx3[!grepl(^(M | T184)”,attempt2$dx3)]使用stru-detect
library(stringr)
library(dplyr)
attempt2 %>%
mutate(dx3 = replace(dx3, !str_detect(dx3, "^(M|T8146)"), ""))
这里有一个方便的库:
library(inops)
attempt2 %out~% c("^M", "^T814") <- ""
库(inops)
尝试2%out~%c(“^M”,“^T814”)对于正则表达式中的“not(多个字符串)”,我相信您的选项是(a)使用负前瞻,或(b)匹配多个字符串,然后求反。您确实不想尝试2$dx3
library(stringr)
library(dplyr)
attempt2 %>%
mutate(dx3 = replace(dx3, !str_detect(dx3, "^(M|T8146)"), ""))
library(inops)
attempt2 %out~% c("^M", "^T814") <- ""