[R] reverse lexicographic order
Gabor Grothendieck
ggrothendieck at myway.com
Tue Dec 16 06:31:42 CET 2003
Here is a way to do it without using apply. sep must be set to
a character not in any of the strings. Below we show its much
faster than using apply yet gives the same answer.
strRev <- function(x, sep = "\10") {
z <- unlist( strsplit( paste( x, sep, sep="" ), "" ) )
z <- unlist( strsplit( paste( rev( z ), collapse="" ), sep ) )
rev( z[-1] )
}
# Following taken from examples in ?strsplit
strReverse <- function(x)
sapply(lapply(strsplit(x,NULL), rev), paste, collapse="")
> data(state)
> system.time(for(i in 1:100)strRev(state.name))
[1] 0.22 0.01 0.23 NA NA
> system.time(for(i in 1:100)strReverse(state.name))
[1] 1.07 0.00 1.83 NA NA
> all.equal(strRev(state.name),strReverse(state.name))
[1] TRUE
---
Date: Tue, 16 Dec 2003 17:41:17 +1300 (NZDT)
From: Richard A. O'Keefe <ok at cs.otago.ac.nz>
To: <r-help at stat.math.ethz.ch>
Subject: Re: [R] reverse lexicographic order
I wrote:
> If anyone can tell me how to vectorise this, I would be glad of the lesson.
where "this" was
> strrev <-
> function (s) paste(rev(strsplit(s, character(0))[[1]]), collapse="")
Thomas Lumley <tlumley at u.washington.edu> suggested
strrev<- function(ss) {
sapply(lapply( strsplit(ss,character(0)), rev), paste, collapse="")
}
Unfortunately, I failed to explain myself clearly, so this doesn't actually
answer the question I _meant_ to ask. For me, sticking in some variant of
'apply' means you have _failed_ to vectorise. The string reversal code in
?rev doesn't count for the same reason.
There is no reason why a built-in strrev() couldn't be as vectorised as
most built-ins, it's just not common enough to deserve a lot of effort.
______________________________________________
R-help at stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help
More information about the R-help
mailing list