From r@vi@v@r@dh@n @ending from jhu@edu  Mon Sep 17 22:22:53 2018
From: r@vi@v@r@dh@n @ending from jhu@edu (Ravi Varadhan)
Date: Mon, 17 Sep 2018 20:22:53 +0000
Subject: [Rd] diag(-1) produces weird result
In-Reply-To: <CABtg=K=XPahEinrnGSRjSJDWgBSEr-ayYx69rNLxsLm2dLJDeg@mail.gmail.com>
References: <C9E6B4F9-DA68-457F-A99A-1D371E4BDE93@revelle.net>,
 <CABtg=K=XPahEinrnGSRjSJDWgBSEr-ayYx69rNLxsLm2dLJDeg@mail.gmail.com>
Message-ID: <406c611762e94f5f984cd180688fe4af@jhu.edu>

It behaves as per documentation.


" Using diag(x) can have unexpected effects if x is a vector that could be of length one. Use diag(x, nrow = length(x)) for consistent behavior."


Ravi


________________________________
From: R-devel <r-devel-bounces at r-project.org> on behalf of G?bor Cs?rdi <csardi.gabor at gmail.com>
Sent: Monday, September 17, 2018 12:22:31 PM
To: lists at revelle.net
Cc: r-devel
Subject: Re: [Rd] diag(-1) produces weird result


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

Gabor
On Mon, Sep 17, 2018 at 5:14 PM William Revelle <lists at revelle.net> wrote:
>
> Dear list
>
> A strange bug in the psych package is due to the behavior of the diag function:
>
> It gives the expected values for 1, a vector (-1,1), but not for -1
>
> Is this a known feature?
>
>
> > diag(1)
>      [,1]
> [1,]    1
> > diag(c(-1,1))
>      [,1] [,2]
> [1,]   -1    0
> [2,]    0    1
> > diag(-1)
> Error in diag(-1) : invalid 'nrow' value (< 0)
>
>
> Bill
>
>
> William Revelle            personality-project.org/revelle.html
> Professor                                 personality-project.org
> Department of Psychology www.wcas.northwestern.edu/psych/<http://www.wcas.northwestern.edu/psych/>
> Northwestern University    www.northwestern.edu/<http://www.northwestern.edu/>
> Use R for psychology         personality-project.org/r
> It is 2   minutes to midnight   www.thebulletin.org<http://www.thebulletin.org>
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel

______________________________________________
R-devel at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel


	[[alternative HTML version deleted]]



[Rd] diag(-1) produces weird result
Ravi Varadhan