Hi, from someone only in his 8th.
m1 <- matrix(c(1,1),c(1,1), nrow = 2, ncol = 2)
m2 <- matrix(c(2,4),c(2,3), nrow = 2, ncol = 2)
the_ms <- list(m1,m1)
lapply(the_ms, eigen)
#> [[1]]
#> eigen() decomposition
#> $values
#> [1] 2 0
#>
#> $vectors
#> [,1] [,2]
#> [1,] 0.7071068 -0.7071068
#> [2,] 0.7071068 0.7071068
#>
#>
#> [[2]]
#> eigen() decomposition
#> $values
#> [1] 2 0
#>
#> $vectors
#> [,1] [,2]
#> [1,] 0.7071068 -0.7071068
#> [2,] 0.7071068 0.7071068
I broke out the matrices from the data frame manually, because a list of matrices is simpler. Give a list of matrices as its first positional argument, lapply
applies its second argument as a function. That's all.
Every R
problem can be thought of with advantage as the interaction of three objects— an existing object, x , a desired object,y , and a function, f, that will return a value of y given x as an argument. In other words, school algebra— f(x) = y. Any of the objects can be composites.
For this problem, one or more matrices serves as x and one or more return values of eigen
serves as y. For only a single matrix, the eigen
functions serves as f. For two or more, x and y becomeslist
s constructed f(g(x)-fashion with lappy
.