N Brouwer
N Brouwer

Reputation: 5078

Matrix operations on objects in a list

I have a list like the one below containing matrices that I want to do separate operations on.

data <- data.frame(matrix(data = c(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2), nrow = 8, ncol = 4, byrow = TRUE) )
matrix_list <- list(data[1:4, ], data[5:8, ])

I know I can do matrix operations on each object separately, like this

eigen(matrix_list[[1]])

And I can do an operation on all items with a for loop

for (i in 1:2){print(eigen((data_list[[i]])))}

How can I skip the for loop and operate on the list directly? It would be great if i could just do something like "eigen(matrix_list)"

Upvotes: 0

Views: 535

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61164

Use lapply to operate over a list

lapply(matrix_list, eigen)
[[1]]
[[1]]$values
[1] 1 1 1 1

[[1]]$vectors
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    1    0
[3,]    0    1    0    0
[4,]    1    0    0    0


[[2]]
[[2]]$values
[1] 2 2 2 2

[[2]]$vectors
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    1    0
[3,]    0    1    0    0
[4,]    1    0    0    0

If you're interested only on values or vectors you can just select them using:

Eigen <- lapply(matrix_list, eigen)
> sapply(Eigen, '[', 'values') # Extrating eigen values
$values
[1] 1 1 1 1

$values
[1] 2 2 2 2

> sapply(Eigen, '[', 'vectors') # Extrating eigen vectors
$vectors
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    1    0
[3,]    0    1    0    0
[4,]    1    0    0    0

$vectors
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    1    0
[3,]    0    1    0    0
[4,]    1    0    0    0

> 

Upvotes: 3

Related Questions