[R] String manipulation and formatting

Marc Schwartz (via MN) mschwartz at mn.rr.com
Mon Jul 17 16:55:08 CEST 2006


On Mon, 2006-07-17 at 16:07 +0200, Bashir Saghir (Aztek Global) 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

Here are two variations:

xify <- function(x)
{
  exxes <- as.numeric(unlist(strsplit(as.character(x), "\\.")))
  ifelse(length(exxes) == 2,
         paste(paste(rep("X", exxes[1] - exxes[2]), collapse = ""), 
               paste(rep("X", exxes[2]), collapse = ""), 
               sep = "."),
         paste(rep("X", exxes[1]), collapse = ""))
}


xify <- function(x)
{
  exxes <- as.numeric(unlist(strsplit(as.character(x), "\\.")))
  tmp <- sapply(exxes, function(x) paste(rep("X", x), collapse = ""))
  ifelse(length(tmp) == 2, 
         paste(substr(tmp[1], 1, exxes[1] - exxes[2]), tmp[2], 
               sep = "."),
         tmp)
}


HTH,

Marc Schwartz



More information about the R-help mailing list