[R] string syntactic sugar in R? - long post
Prof Brian Ripley
ripley at stats.ox.ac.uk
Sat May 7 14:21:18 CEST 2005
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 at 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
More information about the R-help
mailing list