Inverse only alphabetical patterns in a string in R

I am trying to learn R, and the pattern problem only sets the back of the string, which is in alphabetical order:

String: "abctextdefgtext" StringNew: "cbatextgfedtext" 

Is there a way to identify alphabetical patterns for this?

+7
string vector r alphabetical
source share
2 answers

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))) #[1] "cbatextgfedtext" 

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" 
+4
source share

You can do it in the R base

 vec <- match(unlist(strsplit(s, "")), letters) x <- c(0, which(diff(vec) != 1), length(vec)) newvec <- unlist(sapply(seq(length(x) - 1), function(i) rev(vec[(x[i]+1):x[i+1]]))) paste0(letters[newvec], collapse = "") #[1] "cbatextgfedtext" 

Where s <- "abctextdefgtext"

  • First you find the positions of each letter in the sequence of letters ( [1] 1 2 3 20 5 24 20 4 5 6 7 20 5 24 20 )
  • Having positions in your hand, you look for consecutive numbers and, when you find it, cancel this sequence. ( [1] 3 2 1 20 5 24 20 7 6 5 4 20 5 24 20 )
  • Finally, you will get the letters in the last line.
+2
source share

All Articles