3

How to do shift a string in R. I have a string "leaf", when i do a left shift the result should be "flea".

I have tried the shift() function.

But am not able to understand how to do it on a each letter of a string.

Can some one help me

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
Rebe
  • 39
  • 1
  • 6

2 Answers2

4

You can use the following solution with function shifter(s,n), where n is the number of positions to shift (can be zero, any positive or negative integer, not limited to the length of string s):

shifter <- function(s, n) {
  n <- n%%nchar(s)
  if (n == 0) {
    s
  } else {
    paste0(substr(s,nchar(s)-n+1,nchar(s)), substr(s,1,nchar(s)-n))
  }
}

Example

s <- "leaf"
> shifter(s,0)
[1] "leaf"

> shifter(s,1) # shift to right by 1
[1] "flea"

> shifter(s,-1) # shift to left by 1
[1] "eafl"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
3

You can convert it to raw and combine this vector by subsetting the last and the rest.

tt <- charToRaw("leaf")
rawToChar(c(tt[length(tt)], tt[-length(tt)])) #Right shift
#[1] "flea"

rawToChar(c(tt[-1], tt[1])) #Left shift
#[1] "eafl"

In case you have extended characters you can use (thanks to comment from @KonradRudolph)

tt <- strsplit("Äpfel", '')[[1L]]
paste(c(tt[length(tt)], tt[-length(tt)]), collapse = "")  #Right shift
#[1] "lÄpfe"

paste0(c(tt[-1], tt[1]), collapse = "") #Left shift
#[1] "pfelÄ"

or use utf8ToInt and intToUtf8.

tt <- utf8ToInt("Äpfel")
intToUtf8(c(tt[length(tt)], tt[-length(tt)]))
#[1] "lÄpfe"

intToUtf8(c(tt[-1], tt[1]))
#[1] "pfelÄ"
GKi
  • 37,245
  • 2
  • 26
  • 48
  • 1
    Nice idea of converting to raw and back. However, be careful with extended characters. For example, this will fail with the string such as “Äpple”. It’s safer (though more code) to use `strsplit(s, '')[[1L]]` followed by `paste`. – Konrad Rudolph Dec 04 '19 at 08:52
  • @KonradRudolph Many thanks for your comment! I have included it in the Answer. – GKi Dec 04 '19 at 09:03