Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R替换字符串不象两个字符串?_R_Regex_Grepl - Fatal编程技术网

R替换字符串不象两个字符串?

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

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

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") <- ""