[R] reverse string

Gavin Simpson gavin.simpson at ucl.ac.uk
Wed Jul 14 12:36:12 CEST 2010


On Wed, 2010-07-14 at 12:13 +0200, Trafim Vanishek wrote:
> Dear all,
> 
> Are there any functions in R to reverse the order of the string.
> smth like reverse("abc") to get "cba"?

> paste(rev(strsplit("abc", split = "")[[1]]), collapse = "")
[1] "cba"

If your real data is a vector of strings to reverse then

strings <- c("abc","abc","abc")
sapply(strsplit(strings, split = ""),
       function(str) {paste(rev(str), collapse = "")})

is one way to do this.

HTH

G

-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list