[Rd] diag(-1) produces weird result

Barry Rowlingson b@rowling@on @ending from l@nc@@ter@@c@uk
Mon Sep 17 20:08:44 CEST 2018


On Mon, Sep 17, 2018 at 5:22 PM, Gábor Csárdi <csardi.gabor using gmail.com>
wrote:

> I would say it is a mis-feature. If the 'x' argument of diag() is a
> vector of length 1, then it creates an identity matrix of that size,
> instead of creating a 1x1 matrix with the given value:
>
> ❯ diag(3)
>      [,1] [,2] [,3]
> [1,]    1    0    0
> [2,]    0    1    0
> [3,]    0    0    1
>
> Of course this makes it cumbersome to use diag() in a package, when
> you are not sure if the input vector is longer than 1. This seems to
> be a good workaround:
>
> ❯ diag(-1, nrow = 1)
>      [,1]
> [1,]   -1
>
> Or, in general if you have vector v:
>
> ❯ v <- -1
> ❯ diag(v, nrow = length(v))
>      [,1]
> [1,]   -1
> >
>

Anyone else getting deja-vu with the `sample` function?

 > sample(5:3)
 [1] 3 5 4

ok...

 > sample(5:4)
 [1] 4 5

fine...

 > sample(5:5)
 [1] 3 1 5 2 4

uh oh. Documented, of course.

B

	[[alternative HTML version deleted]]



More information about the R-devel mailing list