diag(x, ...) diag.default(x = <<see below>>, nrow = <<see below>>, ncol=<<see below>>) diag(x) <- value
if x is a vector of length greater than one, a matrix with x on its diagonal and zeroes elsewhere.
if x is a vector of length 1 and both nrow and ncol are missing, the value is an x by x identity matrix. By default, the matrix is square with zeros off the diagonal, but it can be made rectangular by specifying nrow and ncol.
the diag(x) <- value form allows replacement of the values on the diagonal of a matrix.
amat <- matrix(c(12,15,6,10,2,9), nrow = 2) diag(amat) # extract diagonal elements ((1,1),(2,2),etc.)diag(diag(amat)) # create a square matrix with # diagonal of amat
diag(5) # 5 by 5 identity matrix diag(nrow = 5) # same thing
diag(as.matrix(5)) # 5
diag(x, nrow = 2*length(x)) # replicate x on the diagonal of a matrix
diag(x, nrow = length(x)) # put x on the diagonal of a matrix # works even if length(x) is 1 or x is a matrix
diag(x) <- diag(y) # put diagonal of y into diagonal of x