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"
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).
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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With