Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting Strings using R functions

Tags:

string

letter

r

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

like image 751
Rebe Avatar asked Sep 25 '26 11:09

Rebe


1 Answers

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"
like image 67
ThomasIsCoding Avatar answered Sep 28 '26 22:09

ThomasIsCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!