Learn R Programming

spam (version 2.1-1)

diag: Sparse Matrix diagonals

Description

Extract or replace the diagonal of a matrix, or construct a diagonal matrix.

Usage

## diag(x)
## diag(x=1, nrow, ncol, names = TRUE)
diag(x) <- value

diag.spam(x=1, nrow, ncol) spam_diag(x=1, nrow, ncol) diag.spam(x) <- value

Arguments

x

a spam matrix, a vector or a scalar.

nrow, ncol

Optional dimensions for the result.

value

either a single value or a vector of length equal to that of the current diagonal.

Value

If x is a spam matrix then diag(x) returns the diagonal of x.

The assignment form sets the diagonal of the sparse matrix x to the given value(s).

diag.spam works as diag for spam matrices: If x is a vector (or 1D array) of length two or more, then diag.spam(x) returns a diagonal matrix whose diagonal is x. spam_diag is an alias for diag.spam and in the spirit of the result of diag is a spam object.

If x is a vector of length one then diag.spam(x) returns an identity matrix of order the nearest integer to x. The dimension of the returned matrix can be specified by nrow and ncol (the default is square).

The assignment form sets the diagonal of the matrix x to the given value(s).

Details

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.

See Also

upper.tri, lower.tri.

Examples

Run this code
# NOT RUN {
diag.spam(2, 4)           # 2*I4
smat <- diag.spam(1:5)
diag( smat)
diag( smat) <- 5:1

# The last line is equivalent to 
diag.spam( smat) <- 5:1

# Note that diag.spam( 1:5) <- 5:1 not work of course.


# }

Run the code above in your browser using DataLab