user7905871
user7905871

Reputation:

Calling the same function over multiple argurment in r?

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), so is there any way to do that easly.

I search lapply families but could not find the answer for my question.

Upvotes: 0

Views: 33

Answers (1)

Pierre Lapointe
Pierre Lapointe

Reputation: 16277

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

Upvotes: 2

Related Questions