Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Reverse a string in R

Tags:

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" 
like image 471
Greg Avatar asked Nov 28 '12 19:11

Greg


People also ask

How do I reverse a number in R?

To create reverse of a number, we can use stri_reverse function of stringi package. For example, if we have a vector called x that contain some numbers then the reverse of these numbers will be generated by using the command stri_reverse(x).


2 Answers

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" 
like image 182
Josh O'Brien Avatar answered Sep 21 '22 23:09

Josh O'Brien


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" 
like image 35
gagolews Avatar answered Sep 21 '22 23:09

gagolews