rnorouzian
rnorouzian

Reputation: 7517

Matrix with the bottom triangle of only `1`s and top triangle of only `0`s in R

I was wondering if there is a way to generate matrices with any requested number of rows and columns such that the bottom triangle is only 1s and top triangle is only 0s.

An example of the expected output is shown below. Is this possible in R?

     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]    1    0    0    0
[3,]    1    1    0    0
[4,]    1    1    1    0
[5,]    1    1    1    1

Upvotes: 0

Views: 60

Answers (1)

MrFlick
MrFlick

Reputation: 206401

You can use the lower.tri helper function

lower_mat <- function(r, c) {
  m <- matrix(0, nrow=r,ncol=c)
  m[lower.tri(m)] <- 1
  m
}

lower_mat(5,4)
#      [,1] [,2] [,3] [,4]
# [1,]    0    0    0    0
# [2,]    1    0    0    0
# [3,]    1    1    0    0
# [4,]    1    1    1    0
# [5,]    1    1    1    1

Upvotes: 4

Related Questions