Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error assigning to a submatrix diagonal with drop=FALSE

Tags:

r

When calling diag<-, you can pass a slice of the matrix and get the proper behavior, as long as you don't specify drop=FALSE.

> X <- matrix(0, 3, 3)
> diag(X[-1,]) <- c(1,2)
> X
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    1    0    0
[3,]    0    2    0

Specifying drop=false is a different story

> diag(X[-1,,drop=FALSE]) <- c(3,4)
Error in diag(X[-1, , drop = FALSE]) <- c(3, 4) : 
  incorrect number of subscripts

Note:

> identical(X[-1,], X[-1,,drop=FALSE])
[1] TRUE

As noted by MrFlick, assignment to a slice when the drop argument results in the same error:

X[1,] <- 1
X[1,,drop=TRUE] <- 2
Error in X[1, , drop = TRUE] <- 2 : incorrect number of subscripts

Why is this happening?

like image 749
Matthew Lundberg Avatar asked Oct 20 '22 09:10

Matthew Lundberg


1 Answers

According to the ?"[<-" help page, drop= "only works for extracting elements, not for the replacement" Thus you are not allowed to use a <- with drop which is basically what diag() is doing. As in my comment above, something like X[,,drop=TRUE] <- 1:9 is not allowed either. Too bad the error message isn't a bit more specific.

like image 149
MrFlick Avatar answered Oct 27 '22 10:10

MrFlick