Re: [R] string syntactic sugar in R? - long post

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Sat 07 May 2005 - 22:21:18 EST

On Sat, 7 May 2005, James Bullard wrote:

> The other thing to use is 'sprintf', which would be fantastic in R if it
> imputed types based on the format string.

But it does in 2.1.0, the current version.

> As it is now, for your query you would do:
>
>> sprintf("SELECT %s FROM table WHERE date = '%s'", "column", "2005-10-12")
> [1] "SELECT column FROM table WHERE date = '2005-10-12'"
>
> Which, in my opinion is nicer than the corresponding paste, and about as nice
> as gstring. The issue that I always have with sprintf is when I use numbers,
> specifically integers. As the function is just a wrapper for the C function

It is not `just a wrapper': someone put a lot of working into writing an intelligent wrapper.

> and because numbers are implicitly doubles the following doesnt work:
>
>> sprintf("SELECT %s FROM table WHERE age = %d", "column", 1)
> Error in sprintf("SELECT %s FROM table WHERE age = %d", "column", 1) :
> use format %f, %e or %g for numeric objects
>
> It does work however if you do
>
>> sprintf("SELECT %s FROM table WHERE age = %d", "column", as.integer(1))
> [1] "SELECT column FROM table WHERE age = 1"
>
> This however, is not so nice - are there reasons why this has to be like
> this? This might be naive but I would think it would be pretty simple in R to
> do this automatically. Thanks for any insight.

In R 2.1.0:

> sprintf("SELECT %s FROM table WHERE age = %d", "column", 1)
[1] "SELECT column FROM table WHERE age = 1"

!

-- 
Brian D. Ripley,                  ripley@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@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 Sat May 07 22:29:14 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:38 EST