How to Reverse a string in R

R

R Problem Overview


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 doesn't seem to have any effect.

There must be something I'm not understanding about lists? (I also don't understand why I need the [[1]] after strsplit.)

> test <- strsplit("greg", NULL)[[1]]
> test
[1] "g" "r" "e" "g"
> test_rev <- rev(test)
> test_rev
[1] "g" "e" "r" "g"
> paste(test_rev)
[1] "g" "e" "r" "g"

R Solutions


Solution 1 - R

From ?strsplit, a function that'll reverse every string in a vector of strings:

## a useful function: rev() for strings
strReverse <- function(x)
        sapply(lapply(strsplit(x, NULL), rev), paste, collapse="")
strReverse(c("abc", "Statistics"))
# [1] "cba"        "scitsitatS"

Solution 2 - R

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"

Solution 3 - R

As @mplourde points out, you want the collapse argument:

paste(test_rev, collapse='')

Most commands in R are vectorized, but how exactly the command handles vectors depends on the command. paste will operate over multiple vectors, combining the ith element of each:

> paste(letters[1:5],letters[1:5])
[1] "a a" "b b" "c c" "d d" "e e"

collapse tells it to operate within a vector instead.

Solution 4 - R

The following can be a useful way to reverse a vector of strings x, and is slightly faster (and more memory efficient) because it avoids generating a list (as in using strsplit):

x <- rep( paste( collapse="", LETTERS ), 100 )
str_rev <- function(x) {
  sapply( x, function(xx) { 
    intToUtf8( rev( utf8ToInt( xx ) ) )
  } )
}
str_rev(x)

If you know that you're going to be working with ASCII characters and speed matters, there is a fast C implementation for reversing a vector of strings built into Kmisc:

install.packages("Kmisc")
str_rev(x)

Solution 5 - R

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"

Solution 6 - R

If your data is in a data.frame, you can use sqldf:

myStrings <- data.frame(forward = c("does", "this", "actually", "work"))
library(sqldf)
sqldf("select forward, reverse(forward) `reverse` from myStrings")
#    forward  reverse
# 1     does     seod
# 2     this     siht
# 3 actually yllautca
# 4     work     krow

Solution 7 - R

Here is a function that returns the whole reversed string, or optionally the reverse string keeping only the elements specified by index, counting backward from the last character.

revString = function(string, index = 1:nchar(string)){
  paste(rev(unlist(strsplit(string, NULL)))[index], collapse = "")
}

First, define an easily recognizable string as an example:

(myString <- paste(letters, collapse = ""))

[1] "abcdefghijklmnopqrstuvwxyz"

Now try out the function revString with and without the index:

revString(myString)

[1] "zyxwvutsrqponmlkjihgfedcba"

revString(myString, 1:5)

[1] "zyxwv"

Solution 8 - R

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,

Solution 9 - R

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"

Solution 10 - R

##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"))
}

Solution 11 - R

The easiest way to reverse string:

#reverse string----------------------------------------------------------------
revString <- function(text){
  paste(rev(unlist(strsplit(text,NULL))),collapse="")
}

#example:
revString("abcdef")

Solution 12 - R

Here is one more base-R solution:

# Define function
strrev <- function(x) {
  nc <- nchar(x)
  paste(substring(x, nc:1, nc:1), collapse = "")
}

# Example
strrev("Sore was I ere I saw Eros")
[1] "sorE was I ere I saw eroS"

Solution was inspired by these U. Auckland slides.

Solution 13 - R

The following Code will take input from user and reverse the entire string-

revstring=function(s)
print(paste(rev(strsplit(s,"")[[1]]),collapse=""))

str=readline("Enter the string:")
revstring(str)

Solution 14 - R

So apparently front-end JS developers get asked to do this (for interviews) in JS without using built-in reverse functions. It took me a few minutes, but I came up with:

string <- 'hello'

foo <- vector()

for (i in nchar(string):1) foo <- append(foo,unlist(strsplit(string,''))[i])
paste0(foo,collapse='')

Which all could be wrapped in a function...

What about higher-order functionals? Reduce?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGregView Question on Stackoverflow
Solution 1 - RJosh O'BrienView Answer on Stackoverflow
Solution 2 - RgagolewsView Answer on Stackoverflow
Solution 3 - RAri B. FriedmanView Answer on Stackoverflow
Solution 4 - RKevin UsheyView Answer on Stackoverflow
Solution 5 - RVen YaoView Answer on Stackoverflow
Solution 6 - RA5C1D2H2I1M1N2O1R2T1View Answer on Stackoverflow
Solution 7 - RPaul 'Joey' McMurdieView Answer on Stackoverflow
Solution 8 - RAnkit DeshmukhView Answer on Stackoverflow
Solution 9 - RSven HohensteinView Answer on Stackoverflow
Solution 10 - RsumalathaView Answer on Stackoverflow
Solution 11 - RUekonometria UekonometriaView Answer on Stackoverflow
Solution 12 - Rsindri_baldurView Answer on Stackoverflow
Solution 13 - Rshivamt042View Answer on Stackoverflow
Solution 14 - RbboppinsView Answer on Stackoverflow