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

## 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



a spam matrix, a vector or a scalar.

nrow, ncol

Optional dimensions for the result.


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


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


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).


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


Reinhard Furrer


diag.spam(2, 4)           # 2*I4
#>      [,1] [,2] [,3] [,4]
#> [1,]    2    0    0    0
#> [2,]    0    2    0    0
#> [3,]    0    0    2    0
#> [4,]    0    0    0    2
#> Class 'spam' (32-bit)
smat <- diag.spam(1:5)
diag( smat)
#> [1] 1 2 3 4 5
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.