[R] Strplit code

John Fox jfox at mcmaster.ca
Wed Dec 3 22:04:55 CET 2008


Dear Brian (and original poster),

My apologies -- I didn't notice the original posting.

By coincidence, I have a version of strsplit() that I've used to
illustrate recursion:

Strsplit <- function(x, split){
    if (length(x) > 1) {
        return(lapply(x, Strsplit, split))  # vectorization
        }
    result <- character(0)
    if (nchar(x) == 0) return(result)
    posn <- regexpr(split, x)
    if (posn <= 0) return(x)
    c(result, substring(x, 1, posn - 1), 
        Recall(substring(x, posn+1, nchar(x)), split))  # recursion
    }

Illustration:

> strings <- c("To be/or not to be/that is the question",
+              "Whether t'is nobler,in the mind",
+              "to suffer the slings:and arrows:of outrageous fortune",
+              "or to take arms;against;a sea of troubles")
     
> Strsplit(strings, "[/,:;]") 
[[1]]
[1] "To be"                "or not to be"         "that is the
question"

[[2]]
[1] "Whether t'is nobler" "in the mind"        

[[3]]
[1] "to suffer the slings"  "and arrows"            "of outrageous
fortune"

[[4]]
[1] "or to take arms"   "against"           "a sea of troubles"



I think that this should work in S-PLUS, though I haven't tried it.

Regards,
 John

On Wed, 3 Dec 2008 20:46:56 +0000 (GMT)
 Prof Brian Ripley <ripley at stats.ox.ac.uk> wrote:
> On Wed, 3 Dec 2008, pomchip at free.fr wrote:
> 
> > Dear R-users,
> >
> > The strsplit function does not exist in S-plus and I would like to
> use it. How
> > could I reproduce the function in Splus or access to its source
> code?
> 
> With difficulty, as it is almost entirely implemented in C code (in
> src/main/character.c and src/main/regex.c, as well as the PCRE
> library)..
> 
> It is not something I would undertake lightly (and I am the
> author/maintainer of most of that code).
> 
> -- 
> Brian D. Ripley,                  ripley at stats.ox.ac.uk
> Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
> University of Oxford,             Tel:  +44 1865 272861 (self)
> 1 South Parks Road,                     +44 1865 272866 (PA)
> Oxford OX1 3TG, UK                Fax:  +44 1865 272595
> 
> ______________________________________________
> 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.

--------------------------------
John Fox, Professor
Department of Sociology
McMaster University
Hamilton, Ontario, Canada
http://socserv.mcmaster.ca/jfox/



More information about the R-help mailing list