 # using map function to calculate eigen values for many dataframes

I want to use map and purr functions to compute eigen values for 3000 matrices. Each matrix has 2 rows and 2 columns. The following code does not work.

test.dat<- tibble(ID=c(1,2),a=c(1,1),b=c(1,1),c=c(2,2),d=c(4,3))

test.out<-test.dat %>% nest(-ID) %>% mutate(fit = purrr::map(data,~ function(x) eigen(matrix(x,2,2)), data=.))

This must be a trivial question for current young practitioners ( In my 9 th decade, I am having fun using R markdown and I am trying to continue my research!) I would greatly appreciate any help.
Thanks.

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)
#> []
#> eigen() decomposition
#> \$values
#>  2 0
#>
#> \$vectors
#>           [,1]       [,2]
#> [1,] 0.7071068 -0.7071068
#> [2,] 0.7071068  0.7071068
#>
#>
#> []
#> eigen() decomposition
#> \$values
#>  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 becomes`list`s constructed f(g(x)-fashion with `lappy`.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.