diags | R Documentation |
Extract diagonals from a matrix.
diags( x, which = 0, incl.labels = c("none", "row", "column"), val.name = "value", label.name = "label" )
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 |
incl.labels |
A single string that indicates whether |
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 |
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.
Derek H. Ogle, derek@derekogle.com, but relied heavily on https://stackoverflow.com/a/27935808/1123933/.
## 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")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.