test.dat <- c("abcde", "abcXe", "abcdY", "abcXY", "abYcXY", "abcYX")
test.want <- c("abcde", "abc1Xe", "abcd1Y", "abc1XY", "abYc1XY", "abcY1X")
Suppose I wish to add "1" before "X" or "Y", and only before "X" if both "X" and "Y" exist.
library(tidyverse)
case_when(
str_detect(test.dat, "X") ~ str_replace(test.dat, "X", "1X"),
str_detect(test.dat, "Y") ~ str_replace(test.dat, "Y", "1Y"),
TRUE ~ as.character(test.dat)
)
This works but is there a better way to do this in concise manner? Perhaps in single str_replace?
How about a second scenario if it was either "X" or "Y" whichever comes first?
test.dat <- c("abcde", "abcXe", "abcdY", "abcXY", "abYcXY", "abcYX")
test.want <- c("abcde", "abc1Xe", "abcd1Y", "abc1XY", "ab1YcXY", "abc1YX")
stringr is preferable but I welcome any other methods. Thank you.