[Rd] diag() when input is a numeric scalar

R. Michael Weylandt michael.weylandt at gmail.com
Thu May 2 12:36:25 CEST 2013

On Thu, May 2, 2013 at 12:35 AM, philchalmers
<rphilip.chalmers at gmail.com> wrote:
> Hi All,
> I'm wondering why when passing a single numeric value that contains any
> decimals to diag() that the value is silently coerced to a integer for
> constructing an identify matrix. To me, an input like diag(5.435) seems
> fairly ambiguous and is more than likely a programming mistake, since it's
> not obvious that a 5x5 identity matrix should be created. I've seen some
> code where other writers have been burned on this as well, especially when
> trying extract diagonal elements but forget about the scalar case. A warning
> or message would help track this problem down really quickly to force the
> author to use diag(floor(5.435)) explicitly, if indeed that is there
> intention. Thoughts?

I agree it's probably rather dangerous, but it does seem consistent
with much of R:

matrix(0, ncol = 3.5)

replicate(2.525, rnorm(3))


So would you propose a global change (the oft talked about "strict
mode") of R or just here? Either way, does this play nicely with R's
goals of having integers and floats behave more or less

That said, I'm slightly confused by a bit of your message: are you
conflating the rounding to integer issue with the different behavior
for scalars issue (same as with sample())?


More information about the R-devel mailing list