VASISTA
VASISTA

Reputation: 33

Remove substring in string and keep some substring

PES+PWA+PWH

I have the above string in R in a data frame, I have to write a script such that if it finds PES then it keeps PES and removes the rest.

I only want PES in the output

Upvotes: 0

Views: 55

Answers (3)

user2793429
user2793429

Reputation: 1

From your question above I assumed you meant you wanted to have only those rows that contain PES?

You can use the grep function in R for that

column<-c("PES-PSA","PES","PWS","PWA","PES+PWA+PWH")
column[grep("PES",column)]
[1] "PES-PSA"     "PES"         "PES+PWA+PWH"

Grep takes the string to match as its first argument and the vector you want to match in as the second.

Upvotes: 0

IRTFM
IRTFM

Reputation: 263352

The grouping operator in R's regex would allow removal of non-"PES" characters:

 gsub("(.*)(PES)(.*)", "\\2", c("PES+PWA+PWH", "something else") )
 #[1] "PES"            "something else"

The problem description wasn't very clear since another respondent nterpreted your request very differntly

Upvotes: 1

Mehdi Nellen
Mehdi Nellen

Reputation: 8964

text <- c("hello", "PES+PWA+PWH", "world")
text[grepl("PES", text)] <- "PES"
# "hello" "PES"   "world"

Upvotes: 1

Related Questions