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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With