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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With