[R] reverse string

Petr PIKAL petr.pikal at precheza.cz
Wed Jul 14 12:47:38 CEST 2010


Hi

Quick glance to strsplit help page 

strReverse <- function(x) sapply(lapply(strsplit(x, NULL), rev), paste, 
collapse="")

Regards
Petr


r-help-bounces at r-project.org napsal dne 14.07.2010 12:36:12:

> 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
> %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list