56

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"
Andrea M
  • 2,314
  • 1
  • 9
  • 27
Greg
  • 45,306
  • 89
  • 231
  • 297

14 Answers14

55

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"
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • 3
    Nice, same function rewritten the dplyr/[magrittr](https://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html) way for readability `strreverse <- function(x){ strsplit(x, NULL) %>% lapply(rev) %>% sapply(paste, collapse="") }`. – Paul Rougieux Jan 28 '16 at 11:17
40

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"
gagolews
  • 12,836
  • 2
  • 50
  • 75
21

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.

Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235
  • So why would I write collapse=''? Wouldn't the '' evaluate to false? Shouldn't I be saying collapse=True? (Still learning my R basics) – Greg Nov 29 '12 at 12:52
  • 1
    @Greg `paste` is a bit non-standard, and I think your intuition is perfectly R-like. However, in this case, `,collapse` works like `,sep` in that it specifies a character to insert in the final character vector. Try `paste(test_rev, collapse='Whee!')` for an illustration. – Ari B. Friedman Nov 29 '12 at 13:06
  • @AriB.Friedman After collapsing it with `paste`, I get `"c(\"l\", \"o\", \"o\", \"c\")"`. But the string was `cool` Whats wrong? –  Oct 19 '16 at 21:22
10

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)
Kevin Ushey
  • 20,530
  • 5
  • 56
  • 88
  • even faster would be `str_rev <- function(x) intToUtf8(rev(utf8ToInt(x)))` and to vectorize it (what your `sapply` does), do str_rev <- Vectorize(str_rev) (but it uses `mapply` under the hood). Are you sure, that `sapply` does not create a list as a intermediate product? Definitely, it is faster than `strsplit`. Nice trick with `utf8ToInt` and `intToUtf8` - thank you! and `rev`. – Gwang-Jin Kim Nov 30 '18 at 14:13
10

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"
Ven Yao
  • 3,680
  • 2
  • 27
  • 42
6

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
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
4

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"

Paul 'Joey' McMurdie
  • 7,295
  • 5
  • 37
  • 41
4

The easiest way to reverse string:

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

#example:
revString("abcdef")
4

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,

  • There is no point in answering 5 year old questions, with 25000 views already. Your answer will be buried somewhere no one will see. Instead answer the latest questions – Anuraag Baishya Mar 26 '18 at 09:15
  • 9
    Nothing wrong with answering old questions. I can see his answer just fine. – DWal Apr 17 '18 at 17:55
1

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"
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
1
##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"))
}
sumalatha
  • 69
  • 1
1

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.

s_baldur
  • 29,441
  • 4
  • 36
  • 69
1

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)
DavidG
  • 24,279
  • 14
  • 89
  • 82
shivamt042
  • 19
  • 3
0

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?

bboppins
  • 11
  • 2