Reputation: 33
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
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
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
Reputation: 8964
text <- c("hello", "PES+PWA+PWH", "world")
text[grepl("PES", text)] <- "PES"
# "hello" "PES" "world"
Upvotes: 1