fork download
  1. # If you need to add 1 to the end of strings not having X or Y
  2. test.dat <- c("abcde", "abcXe", "abcdY", "abcXY", "abYcXY", "abcYX")
  3. sub("^([^XY]*)$", "\\11", sub("^([^XY]*)(Y)([^X]*)$|(.*)(X)", "\\1\\41\\3\\5\\2", test.dat))
  4.  
  5. library(stringr)
  6. str_replace(str_replace(test.dat, "^([^XY]*)(Y)([^X]*)$|(.*)(X)", "\\1\\41\\3\\5\\2"), "^([^XY]*)$", "\\11")
Success #stdin #stdout 0.25s 42428KB
stdin
Standard input is empty
stdout
[1] "abcde1"  "abc1Xe"  "abcd1Y"  "abc1XY"  "abYc1XY" "abcY1X" 
[1] "abcde1"  "abc1Xe"  "abcd1Y"  "abc1XY"  "abYc1XY" "abcY1X"