Pregunta

I want to extract part of a string but with an if condition. So that I dont extract anything if this if condition is true.

my code sofar

u<-c("18 ABC TEST1 17","ABC 18")

u<-ifelse((grepl("(TEST2|TEST1|)",u,perl=T)==F)&(grepl("^(.*) ?([A-Z]+) ?(.*)",u,perl=T)==T) ,"\\1 \\2",u))

So far I got

c("18 ABC TEST1 17","\\1 \\2")

But i want

c("18 ABC TEST1 17","ABC")

Thanks in advance

¿Fue útil?

Solución

I am not sure what do you want to extract but following will help you get started.

grepl will return vector of boolean values based on which ifelse will element-wise choose from vector u or vector resulting from gsub("^(.*) ?([A-Z]+) ?(.*)", "\\1 \\2", u)

ifelse((grepl("(TEST2|TEST1)", u, perl = T)), u, gsub("^(.*) ?([A-Z]+) ?(.*)", "\\1 \\2", u))
## [1] "18 ABC TEST1 17" "AB C" 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top