Shifting Strings using R functions

杀马特。学长 韩版系。学妹 提交于 2020-02-24 05:36:26

问题


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


回答1:


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"



回答2:


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


来源:https://stackoverflow.com/questions/59171164/shifting-strings-using-r-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!