How to Reverse a string in R

后端 未结 14 2088
花落未央
花落未央 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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"))
    }
    

提交回复
热议问题