Search code examples
rmatrixdeterminants

Reiterating through a list of matrices in R


I am trying to go through a list of matrices (matList) to take the determinant of each matrix, and return a new list of all the determinant values.

So far, I have tried this:

matList

detList <- list()
for(i in matList){
  detList <- c(det(matList[i]))
  i + 1 
}

detList

But I get the error message: Error in UseMethod("determinant") : no applicable method for 'determinant' applied to an object of class "list"

I know I can't take a determinant of a list but I called that function to each matrix, so I am not sure why I am getting this error message or how to fix it.


Solution

  • I think this is textbook example for using lapply (or sapply for that matter). Does

    detList <- lapply(matList, det)
    

    work?

    It is functionally equivalent to

    detList <- list()
    for (i in matList){
      detList[i] <- det(matList[[i]])
    }
    

    which would be the proper loop as explained by @joran in the comments.