Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

diags

Extract diagonals from a matrix.


Description

Extract diagonals from a matrix.

Usage

diags(
  x,
  which = 0,
  incl.labels = c("none", "row", "column"),
  val.name = "value",
  label.name = "label"
)

Arguments

x

A matrix with more than one row AND more than one column.

which

A single numeric that indicates which diagonal to extract. A value of zero extracts the main diagonal, whereas negative values extract diagonals from the upper triangle and positive values extract diagonals from the lower triangle. Diagonals further from the main diagonal have which values further from zero. If is.null(which), then a matrix of diagonal indices for which is shown.

incl.labels

A single string that indicates whether "row", "column", or no ("none") labels from x should be returned with the values on the diagonal. Will return numeric values if the labels are all diagonal, otherwise character labels are returned.

val.name

A single string to name the variable that contains the values from the diagonal in the returned data.frame.

label.name

A single string to name the variable that contains the labels in the returned data.frame (see incl.labels)

Value

A data.frame with one variable that contains the values from the chosen diagonal of x and, optionally, a second variable that contains the chosen labels for those values.

Author(s)

Examples

## Square numeric matrix
mat1 <- matrix(1:16,nrow=4)
colnames(mat1) <- LETTERS[1:ncol(mat1)]
rownames(mat1) <- 1:nrow(mat1)
mat1
diags(mat1,which=NULL)
diags(mat1)
diags(mat1,which=-1)
diags(mat1,which=2)
diags(mat1,incl.labels="row")
diags(mat1,which=2,incl.labels="row")
diags(mat1,which=2,incl.labels="col")
( tmp <- diags(mat1,which=2,incl.labels="row",val.name="Freq",label.name="age") )
str(tmp)

## Rectangular numeric matrix
mat2 <- matrix(1:20,nrow=4)
colnames(mat2) <- LETTERS[1:ncol(mat2)]
rownames(mat2) <- 1:nrow(mat2)
mat2
diags(mat2,which=NULL)
diags(mat2,which=-1,incl.labels="row")
diags(mat2,which=2,incl.labels="row")
diags(mat2,which=-4,incl.labels="col")

## Rectangular character matrix
mat3 <- matrix(LETTERS[1:24],nrow=3)
colnames(mat3) <- letters[1:ncol(mat3)]
rownames(mat3) <- 1:nrow(mat3)
mat3
diags(mat3,which=NULL)
diags(mat3,which=-1,incl.labels="row")
diags(mat3,which=2,incl.labels="row")
diags(mat3,which=-4,incl.labels="col")

FSA

Simple Fisheries Stock Assessment Methods

v0.8.32
GPL (>= 2)
Authors
Derek Ogle [aut, cre] (<https://orcid.org/0000-0002-0370-9299>), Powell Wheeler [aut], Alexis Dinno [aut] (Provided base functionality of dunnTest())
Initial release
2021-1-15

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.