Learn R Programming

posterior (version 1.6.0)

diag,rvar-method: Matrix diagonals (including for random variables)

Description

Extract the diagonal of a matrix or construct a matrix, including random matrices (2-dimensional rvars). Makes base::diag() generic.

Usage

# S4 method for rvar
diag(x = 1, nrow, ncol, names = TRUE)

Value

For rvars, has two modes:

  1. x is a matrix-like rvar: it returns the diagonal as a vector-like rvar

  2. x is a vector-like rvar: it returns a matrix-like rvar with x as the diagonal and zero for off-diagonal entries.

Arguments

x

(numeric,rvar) a matrix, vector, 1D array, missing, or a 1- or 2-dimensional rvar.

nrow, ncol

optional dimensions for the result when x is not a matrix.

names

(when x is a matrix) logical indicating if the resulting vector, the diagonal of x, should inherit names from dimnames(x) if available.

Details

Makes base::diag() into a generic function. See that function's documentation for usage with numerics and for usage of diag<-, which is also supported by rvar.

See Also

Examples

Run this code

# Sigma is a 3x3 covariance matrix
Sigma <- as_draws_rvars(example_draws("multi_normal"))$Sigma
Sigma

diag(Sigma)

diag(Sigma) <- 1:3
Sigma

diag(as_rvar(1:3))

Run the code above in your browser using DataLab