I need help with finding a pattern and replacing it by two different ways. For example, the word "Code/i"
should be replaced with "Code, Codi"
.
What code should I use in replacement to get two results separated by comma? I am new to R and assuming some metacharacters or regex needs to be used? Also, i need to use base functions and no external packages. Appreciate any feedback and help as im stuck! Thanks
a <- c("Code/i", "Karina")
gsub(pattern = "/i", replacement= "", a)
Desired outcome:
"Code, Codi, Karina"
You can use sub
and paste0
and subset your vector a
on the relevant values (those that contain the pattern /
):
Data:
a <- c("Code/i", "Karina", "Jimmy", "John Bolton", "Pete/i")
Solution:
c(paste0(sub("/.*", "", a[grepl("/", a)]), ", ", sub("./", "", a[grepl("/", a)])), a[!grepl("/", a)])
Result:
[1] "Code, Codi" "Pete, Peti" "Karina" "Jimmy" "John Bolton"