Extract or replace the upper/lower triangular portion of a matrix

Share:

Description

Extract or replace the upper/lower triangular portion of a matrix

Usage

1
2
3
4
upperTriangle(x, diag=FALSE, byrow=FALSE)
upperTriangle(x, diag=FALSE, byrow=FALSE) <- value
lowerTriangle(x, diag=FALSE, byrow=FALSE)
lowerTriangle(x, diag=FALSE, byrow=FALSE) <- value

Arguments

x

Matrix

diag

Logical. If TRUE, include the matrix diagonal.

byrow

Logical. If FALSE, return/replace elements in column-wise order. If TRUE, return/replace elements in row-wise order.

value

Either a single value or a vector of length equal to that of the current upper/lower triangular. Should be of a mode which can be coerced to that of x.

Value

upperTriangle(x) and lowerTriangle(x) return the upper or lower triangle of matrix x, respectively. The assignment forms replace the upper or lower triangular area of the matrix with the provided value(s).

Note

By default, the elements are returned/replaced in R's default column-wise order. Thus

1

will not yield a symmetric matrix. Instead use:

1
  lowerTriangle(x) <- upperTriangle(x, byrow=TRUE)

or equivalently:

1
  lowerTriangle(x, byrow=TRUE) <- upperTriangle(x)

Author(s)

Gregory R. Warnes greg@warnes.net

See Also

diag, lower.tri, upper.tri

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  x <- matrix( 1:25, nrow=5, ncol=5)
  x
  upperTriangle(x)
  upperTriangle(x, diag=TRUE)
  upperTriangle(x, diag=TRUE, byrow=TRUE)


  lowerTriangle(x)
  lowerTriangle(x, diag=TRUE)
  lowerTriangle(x, diag=TRUE, byrow=TRUE)

  upperTriangle(x) <- NA
  x

  upperTriangle(x, diag=TRUE) <- 1:15
  x

  lowerTriangle(x) <- NA
  x

  lowerTriangle(x, diag=TRUE) <- 1:15
  x

  ## Copy lower triangle into upper triangle to make 
  ## the matrix (diagonally) symmetric
  x <- matrix(LETTERS[1:25], nrow=5, ncol=5, byrow=TRUE)
  x
  lowerTriangle(x) = upperTriangle(x, byrow=TRUE)
  x

Want to suggest features or report bugs for rdrr.io? Use the GitHub issue tracker.