Here is one approach with base R based on the patterns shown in the example. We will split the string into separate characters ('v1'), use match to find the position of characters with the alphabetical position ( letters ), get the difference between the index and check if it is equal to 1 ('i1'). Using a logical vector, we multiply the vector ('v1'), create a grouping variable and the inverse ( rev ) vector based on the grouping variable. Finally, paste characters together to get the expected output
v1 <- strsplit(str1, "")[[1]] i1 <- cumsum(c(TRUE, diff(match(v1, letters)) != 1L)) paste(ave(v1, i1, FUN = rev), collapse="") #[1] "cbatextgfedtext"
Or like @alexislaz mentioned in the comments
v1 = as.integer(charToRaw(str1)) rawToChar(as.raw(ave(v1, cumsum(c(TRUE, diff(v1) != 1L)), FUN = rev)))
EDIT:
1) The error has been fixed based on comments @alexislaz
2) Updated by another method suggested by @alexislaz in the comments
data
str1 <- "abctextdefgtext"
akrun
source share