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

From: Ted Harding <>
Date: Sat 07 May 2005 - 20:26:39 EST

On 07-May-05 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.
> 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 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.

You can force integer format using %f if you use it as "%.0f":

  sprintf("SELECT %s FROM table WHERE age = %.0f", "column", 1)   ## [1] "SELECT column FROM table WHERE age = 1"

The rule (as in C) is that "" outputs a format for the floating-point number in a minimum width of 'a' characters ("field width", left-padded with space), with 'b' digits following the decimal point (and no decimal point is printed if b=0); if either 'a' or 'b' is missing then no corresponding restriction is imposed.

Best wishes,

E-Mail: (Ted Harding) <> Fax-to-email: +44 (0)870 094 0861
Date: 07-May-05                                       Time: 11:05:06
------------------------------ XFMail ------------------------------

______________________________________________ mailing list PLEASE do read the posting guide! Received on Sat May 07 20:42:46 2005

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