Alice - 1 year ago 58
R Question

# 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.

`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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download