Re: [R] String manipulation and formatting

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Tue 18 Jul 2006 - 01:22:06 EST

In thinking about this some more it can be substantially simplified. We don't need f at all -- we can just use repx and we don't need any backreferences either since we can repeatedly apply the numeric pattern. This reduces it to a two line body:

library(gsubfn)
xify <- function(fmt) {

   repx <- function(n) paste(rep("X", n), collapse = "")    as.vector(gsubfn("[[:digit:]]+", repx, as.character(fmt))) }

xify(5.2) # XXXXX.XX
xify(5) # XXXXX

On 7/17/06, Gabor Grothendieck <ggrothendieck@gmail.com> wrote:
> First we define repx(n) to produce n X's. This
> simple function is used subsequently. f is a
> function that takes 4 strings which represent the
> entire string and the three backreferenced substrings
> in the subsequent gsub pattern and does the paste.
> x1 will represent the part before the dot and x3 after
> the dot. x2 represents the dot plus x3 and is not used.
> Finally we run gsubfn using the appropriate regex pattern.
>
> library(gsubfn)
> xify <- function(fmt) {
> repx <- function(n) paste(rep("X", n), collapse = "")
> f <- function(x, x1= "", x2 = "", x3 = "")
> if (x3 == "") repx(x1) else paste(repx(x1), ".", repx(x3), sep = "")
> as.vector(gsubfn("^([[:digit:]]+)(.([[:digit:]])|)", f, as.character(fmt)))
> }
>
> xify(5.2) # XXXXX.XX
> xify(5) # XXXXX
>
>
> On 7/17/06, Bashir Saghir (Aztek Global) <Saghir.Bashir@ucb-group.com> wrote:
> > I'm trying to write a simple function that does the following:
> >
> > [command] xify(5.2)
> > [output] XXX.XX
> >
> > [command] xify(3)
> > [output] XXX
> >
> > Any simple solutions (without using python/perl/unix script/...)?
> >
> > Thanks,
> > Saghir
> >
> >
> > ---------------------------------------------------------
> > Legal Notice: This electronic mail and its attachments are i...{{dropped}}
> >
> > ______________________________________________
> > R-help@stat.math.ethz.ch mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
> >
>



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Tue Jul 18 01:25:43 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 18 Jul 2006 - 20:16:58 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.