How to Reverse a string in R
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"
Solution 1:
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:
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:
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 i
th 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.