Extract the diagonal of a matrix or construct a matrix, including random
matrices (2-dimensional rvar
s). Makes base::diag()
generic.
# S4 method for rvar
diag(x = 1, nrow, ncol, names = TRUE)
For rvar
s, has two modes:
Makes base::diag()
into a generic function. See that function's documentation
for usage with numeric
s and for usage of diag<-
, which is also supported
by rvar
.
# Sigma is a 3x3 covariance matrix
Sigma <- as_draws_rvars(example_draws("multi_normal"))$Sigma
Sigma
#> rvar<100,4>[3,3] mean ± sd:
#> [,1] [,2] [,3]
#> [1,] 1.28 ± 0.17 0.53 ± 0.20 -0.40 ± 0.28
#> [2,] 0.53 ± 0.20 3.67 ± 0.45 -2.10 ± 0.48
#> [3,] -0.40 ± 0.28 -2.10 ± 0.48 8.12 ± 0.95
diag(Sigma)
#> rvar<100,4>[3] mean ± sd:
#> [1] 1.3 ± 0.17 3.7 ± 0.45 8.1 ± 0.95
diag(Sigma) <- 1:3
Sigma
#> rvar<100,4>[3,3] mean ± sd:
#> [,1] [,2] [,3]
#> [1,] 1.00 ± 0.00 0.53 ± 0.20 -0.40 ± 0.28
#> [2,] 0.53 ± 0.20 2.00 ± 0.00 -2.10 ± 0.48
#> [3,] -0.40 ± 0.28 -2.10 ± 0.48 3.00 ± 0.00
diag(as_rvar(1:3))
#> rvar<1>[3,3] mean ± sd:
#> [,1] [,2] [,3]
#> [1,] 1 ± NA 0 ± NA 0 ± NA
#> [2,] 0 ± NA 2 ± NA 0 ± NA
#> [3,] 0 ± NA 0 ± NA 3 ± NA