[R] string syntactic sugar in R? - long post
(Ted Harding)
Ted.Harding at nessie.mcc.ac.uk
Sat May 7 12:26:39 CEST 2005
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 "%a.bf" 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,
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 07-May-05 Time: 11:05:06
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list