Alice - 3 months ago 17

R Question

Suppose I have three matrices:

`Mat1 = matrix(0,4,4)`

Mat2 = matrix(0,4,4)

Mat3 = matrix(0,4,4)

Then suppose that I need to create numbers of matrix is very difficult to do that manually. Also, I want to make these function as a low triangle matrix using

`low.tri(Mat1)`

I search

`lapply`

Answer Source

`lapply`

is used on lists. First, you insert all your matrices in a `list`

. `lower.tri`

is a logical function. If you want to get a lower triangle, you should create a function similar to `f`

below. Then you can use `lapply`

like so:

```
Mat1 = matrix(0,4,4)
Mat2 = matrix(0,4,4)
Mat3 = matrix(0,4,4)
l <- list(Mat1,Mat2,Mat3)
f <- function(m) {
m[lower.tri(m)] <- 1
m
}
lapply(l,f)
[[1]]
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 1 0 0 0
[3,] 1 1 0 0
[4,] 1 1 1 0
[[2]]
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 1 0 0 0
[3,] 1 1 0 0
[4,] 1 1 1 0
[[3]]
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 1 0 0 0
[3,] 1 1 0 0
[4,] 1 1 1 0
```