[R] String manipulation and formatting

Gabor Grothendieck ggrothendieck at gmail.com
Mon Jul 17 17:06:20 CEST 2006


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 at 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 at 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
>



More information about the R-help mailing list