如何在 R 中移动字符串。
我有一个字符串“leaf”,当我左移时,结果应该是“flea”。

我试过 shift() 函数。

但是我无法理解如何在字符串的每个字母上执行此操作。

有人能帮我吗

最佳答案

您可以将以下解决方案与函数 shifter(s,n) 一起使用,其中 n 是要移位的位置数(可以是零、任何正整数或负整数,不限于字符串 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))
  }
}

示例
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"

关于r - 使用 R 函数移动字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59171164/

10-12 17:52
查看更多