[Rd] sprintf, check number of parameters
Matthias Gondan
m@tth|@@-gond@n @end|ng |rom gmx@de
Sat Feb 6 14:11:53 CET 2021
Dear developers,
This is a follow-up from an earlier mail about warnings of unused arguments in sprintf:
1. This should obviously raise an error (and it does):
sprintf('%i %i', 1)
Fehler in sprintf("%i %i", 1) : zu wenig Argumente [= too few arguments]
2. This should, in my opinion, raise a warning about an unused argument (and I think it does in now R-devel):
sprintf('%i', 1, 2)
3. From the conversation below, it seems that this also raises a warning (in R-devel):
sprintf('%1$i', 1, 2)
I think that one should be suppressed. When I reported this a few months ago, I didn’t really have a use case for (3), but now I think I have found something. Suppose I have a function that calculates some descriptive statistics, mean, sd, available cases, missings, something like the one below:
msnx = function(x, mask='%1$.1f (SD=%2$.1f, n=%3$i, NA=%4$i)')
{
m = mean(x, na.rm=TRUE)
s = sd(x, na.rm=TRUE)
n = sum(!is.na(x))
na = sum(is.na(x))
sprintf(mask, m, s, n, na)
}
The mask is meant to help formatting it a bit.
msnx(T0)
[1] "30.7 (SD=4.7, n=104, NA=0)"
Now I want a „less detailed“ summary, so I invoke the function with something like
msnx(T0, mask='%1$.1f (SD=%2$.1f)')
[1] "30.7 (SD=4.7)"
In my opinion, in the last example, sprintf should not raise the warning in (2) if all arguments in the mask are „dollared“. I am still a bit unsure since the example uses a function that calculate things that aren’t being used (n and na), and this could be considered bad programming style. But there might be other use cases, and it is, nevertheless, a deliberate choice to skip arguments 3$ and 4$.
Best wishes,
Matthias
Dear Matthias,
thanks for the suggestion, R-devel now warns on unused arguments by
format (both numbered and un-numbered). It seems that the new warning is
useful, often it finds cases when arguments were accidentally passed to
sprintf but had been meant for a different function.
R allows combining both numbered and un-numbered references in a single
format, even though it may be better to avoid and POSIX does not allow
that.
Best
Tomas
On 9/20/20 1:03 PM, Matthias Gondan wrote:
> Dear R developers,
>
> I am wondering if this should raise an error or a warning.
>
>> sprintf('%.f, %.f', 1, 2, 3)
> [1] "1, 2"
>
> I am aware that R has „numbered“ sprintf arguments (sprintf('%1$.f', …), and in that case, omissing of specific arguments may be intended. But in the usual syntax, omission of an argument is probably a mistake.
>
> Thank you for your consideration.
>
> Best wishes,
>
> Matthias
[[alternative HTML version deleted]]
More information about the R-devel
mailing list