Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace entire strings based on partial match

Tags:

regex

r

New to R. Looking to replace the entire string if there is a partial match.

d = c("SDS0G2 Blue", "Blue SSC2CWA3", "Blue SA2M1GC", "SA5 Blue CSQ5")

gsub("Blue", "Red", d, ignore.case = FALSE, fixed = FALSE)

Output: "SDS0G2 Red" "Red SSC2CWA3" "Red SA2M1GC" "SA5 Red CSQ5"

Desired Output: “Red” “Red” “Red” “Red”

Any help in solving this is truly appreciated.

like image 988
user3422112 Avatar asked Mar 15 '14 02:03

user3422112


1 Answers

I'd suggest using grepl to find the indices and replace those indices with "Red":

d = c("SDS0G2 Blue", "Blue SSC2CWA3", "Blue SA2M1GC", "SA5 Blue CSQ5", "ABCDE")
d[grepl("Blue", d, ignore.case=FALSE)] <- "Red"
d
# [1] "Red"   "Red"   "Red"   "Red"   "ABCDE"
like image 126
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 21 '22 16:09

A5C1D2H2I1M1N2O1R2T1