0

Why is output not equal to a 1 * 1 matrix here?

EDIT : the strange behaviour comes from the diag function

dist <- adist("errors", "eror", costs = c(1, 1, 1), counts = T)
dist

    [,1]
[1,]    2
attr(,"counts")
, , ins

     [,1]
[1,]    0

, , del

     [,1]
[1,]    2

, , sub

     [,1]
[1,]    0

attr(,"trafos")
     [,1]    
[1,] "MDMMMD"

# But when one element of the array is accessed, it's a 0 x 0 matrix
output <- diag(attr(dist, which = "counts")[ , , "ins"]) # or [ , , 1]
output
<0 x 0 matrix>
Julien
  • 1,613
  • 1
  • 10
  • 26
  • Yes, `attr(dist, which = "counts")[ , , "ins"]` outputs a vector which `= 0`, so `diag` returns a diagonal matrix of size 0 – Maël Mar 07 '23 at 08:37
  • Why is this behaviour relevant? – Julien Mar 07 '23 at 08:38
  • It's not really mentioned in the documentation, but what else would you expect? `diag` converts to `matrix` object, but it returns an empty object. – Maël Mar 07 '23 at 08:41
  • I would expect `0` – Julien Mar 07 '23 at 08:43
  • 1
    When you provide one digit n to the `diag` function, it will create a diagonal matrix of size n, so if it 0, it will give a diagonal matrix of size 0, if 2 it'll give `matrix(c(1, 0, 0, 1), nrow = 2)` – Maël Mar 07 '23 at 08:45
  • In the doucmentation it's written : "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 behaviour. – Julien Mar 07 '23 at 08:45
  • I don't understand what you are trying to achieve with `diag`. You have two options. Subset as you have been doing, then the result is a vector and a diagonal is not defined. Or, subset with `[ , , "ins", drop = FALSE]`, then the result is a 3D array and a matrix diagonal is not defined. – Roland Mar 07 '23 at 08:45
  • `[ , , "ins", drop = FALSE]` produces an error – Julien Mar 07 '23 at 08:48
  • Obviously, because you are trying to get the matrix diagonal of a 3D array. – Roland Mar 07 '23 at 09:32

0 Answers0