How to Reverse a string in R

后端 未结 14 1950
花落未央
花落未央 2020-11-27 03:29

I\'m trying to teach myself R and in doing some sample problems I came across the need to reverse a string.

Here\'s what I\'ve tried so far but the paste operation d

相关标签:
14条回答
  • 2020-11-27 03:57

    You can do with rev() function as mentioned in a previous post.

    `X <- "MyString"
    

    RevX <- paste(rev(unlist(strsplit(X,NULL))),collapse="")

    Output : "gnirtSyM"

    Thanks,

    0 讨论(0)
  • 2020-11-27 03:59

    You can also use the IRanges package.

    library(IRanges)
    x <- "ATGCSDS"
    reverse(x)
    # [1] "SDSCGTA"
    

    You can also use the Biostrings package.

    library(Biostrings)
    x <- "ATGCSDS"
    reverse(x)
    # [1] "SDSCGTA"
    
    0 讨论(0)
  • 2020-11-27 04:00

    The easiest way to reverse string:

    #reverse string----------------------------------------------------------------
    revString <- function(text){
      paste(rev(unlist(strsplit(text,NULL))),collapse="")
    }
    
    #example:
    revString("abcdef")
    
    0 讨论(0)
  • 2020-11-27 04:01
    ##function to reverse the given word or sentence
    
    reverse <- function(mystring){ 
    n <- nchar(mystring)
    revstring <- rep(NA, n)
    b <- n:1
    c <- rev(b)
    for (i in 1:n) {
    revstring[i] <- substr(mystring,c[(n+1)- i], b[i])
     }
    newrevstring <- paste(revstring, sep = "", collapse = "")
    return (cat("your string =", mystring, "\n",
    ("reverse letters = "), revstring, "\n", 
    "reverse string =", newrevstring,"\n"))
    }
    
    0 讨论(0)
  • 2020-11-27 04:09

    Here's a solution with gsub. Although I agree that it's easier with strsplit and paste (as pointed out in the other answers), it may be interesting to see that it works with regular expressions too:

    test <- "greg"
    
    n <- nchar(test) # the number of characters in the string
    
    gsub(paste(rep("(.)", n), collapse = ""),
         paste("", seq(n, 1), sep = "\\", collapse = ""),
         test)
    
    # [1] "gerg"
    
    0 讨论(0)
  • 2020-11-27 04:10

    stringi has had this function for quite a long time:

    stringi::stri_reverse("abcdef")
    ## [1] "fedcba"
    

    Also note that it's vectorized:

    stringi::stri_reverse(c("a", "ab", "abc"))
    ## [1] "a"   "ba"  "cba"
    
    0 讨论(0)
提交回复
热议问题