-1

I am trying to find the sum of determinant of matrices present inside a list using lapply. In the list not all items are a matrix.

I have a list with three elements e.g.

[[1]]
    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1            5.1         3.5          1.4         0.2     setosa
2            4.9         3.0          1.4         0.2     setosa
3            4.7         3.2          1.3         0.2     setosa
ETC... 

[[2]]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

[[3]]
 [1]  1  2  3  4  5  6  7  8  9 10

I am aware I need to check if an item in a list is a matrix using is.matrix() however cannot seem to get this to work.

lapply(list1, function(x){ (is.matrix(x)) })

Returns:

[[1]]
[1] FALSE

[[2]]
[1] TRUE

[[3]]
[1] FALSE

I am unsure where to go from here as I cannot perform det(x) on a list or even element of a list such as the below:

det(list1[2])

Output:

> det(list1[2])
Error in UseMethod("determinant") : 
  no applicable method for 'determinant' applied to an object of class "list"

Any help would greatly be appreciated!

falconed
  • 29
  • 3
  • So what is your expected output, based on the sample list you give? Is it a `list` of length equal to your input `list`, with elements equal to the determinant of matrix elements and `NA` else? Or something similar? Please be specific. – Maurits Evers Aug 28 '22 at 12:41

1 Answers1

0

Are you after something like this?

lapply(lst, \(x) {if (is.matrix(x)) det(x) else NA })
#[[1]]
#[1] NA
#
#[[2]]
#[1] 0
#
#[[3]]
#[1] NA

Or if you're only interested in getting the determinant for the 2nd element of lst

det(lst[[2]])
#[1] 0

Note the double square brackets to select a specific element from a list.


Sample data

lst <- list(iris, matrix(1:9, ncol = 3), 1:10)
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68