[R] String manipulation and formatting

Hans-Joerg Bibiko bibiko at eva.mpg.de
Tue Jul 18 11:47:28 CEST 2006


Hi,

only if you allow to input x as a string then you can use, maybe,  
simply the following one-line-command:

xify <- function(x)
{
	gsub(
		"[0-9]",
		"X",
		sprintf(
			paste("%",ifelse(regexpr("\\.",x) > 0, x, x<-paste(x,". 
0",sep="")), "f",sep=""),
			10^(trunc(as.numeric(x))-as.integer(gsub("(.*?)\\.(.*?)","\\2",x))-1)
		)
	)
}

 > xify("30.10")
  [1] "XXXXXXXXXXXXXXXXXXXX.XXXXXXXXXX"

Hans-Joerg


>>> Thanks to Richard, Gabor and Marc for some nice solutions to my  
>>> request.
>>>
>>> I have a new problem:
>>>
>>>> xify(30.10)
>>>   [1] "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX.X"
>>>> xify(30.11)
>>>   [1] "XXXXXXXXXXXXXXXXXXX.XXXXXXXXXXX"
>>>
>>> The problem originates from:
>>>
>>>> as.numeric(unlist(strsplit(as.character(15.10), "\\.")))
>>>   [1] 15  1
>>>> as.numeric(unlist(strsplit(as.character(15.11), "\\.")))
>>>   [1] 15 11
>>>
>>> It seems to boils down to:
>>>
>>>> as.character(15.10)
>>>   [1] "15.1"
>>>
>>> A simple solution is:
>>>
>>>> xify("15.10")
>>>   [1] "XXXXX.XXXXXXXXXX"
>>>
>>> I was wondering if there is a simple way for xify to see the zero  
>>> of the
> 10
>>> without having to force the user to add quotes around the format?
>>
>> No, as the parser has converted '15.10' to a numeric constant.
>>
>> What is the problem with asking users to enter strings as strings?
>>



More information about the R-help mailing list