Rebe
Rebe

Reputation: 41

Shifting Strings using R functions

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

Upvotes: 3

Views: 1843

Answers (2)

GKi
GKi

Reputation: 39657

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Ä"

Upvotes: 3

ThomasIsCoding
ThomasIsCoding

Reputation: 101189

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"

Upvotes: 4

Related Questions