jd06340
jd06340

Reputation: 73

Using lapply to create 0's in upper triangle of a list of matrices

I have a list of matrices of mostly similar sizes. I need to keep the upper triangle of each matrix equal to 0. I can make the upper tri of an individual matrix equal to 0 by using:

matrix[upper.tri(matrix)] <- 0

When I try to apply this to the list of matrices using lapply it replaces the entire matrix list with 0's. For example:

list.matrix <- lapply(list.matrix, function (x) x[upper.tri(x)] <- 0)

$`matrix1`
[1] 0
$`matrix2`
[1] 0
...

Can anyone provide input as to why this might be happening?

Upvotes: 2

Views: 89

Answers (2)

akrun
akrun

Reputation: 887501

We can use replace

f <- function(x) replace(x, upper.tri(x), 0)
f(m1)

data

m1 <- matrix(1:9, 3, 3)

Upvotes: 1

jd06340
jd06340

Reputation: 73

This was resolved by including the function in lapply as a new function:

f <- function(x) {
  x[upper.tri(x)] <- 0
  x
}

as suggested here: lapply to turn specified matrix elements within list to NA.

Upvotes: 2

Related Questions