Search code examples
rlistmatrixlapplycovariance

Errors in creating a list of (covariance) matrices using lapply in R


I have this formula, which creates a large list of 251 elements:

lapply(2:nrow(mat), function(y) cov(mat[1:y,]))

mat has dim():

[1] 252  80

But I want it to start from 1, i.e. 1:nrow(mat) such that I get 252 elements similar to nrow(mat). However changing 2:nrow(mat) to 1:nrow(mat) produces this error message:

lapply(1:nrow(mat), function(y) cov(mat[1:y,]))

Error in cov(mat[1:y, ]) : 
  supply both 'x' and 'y' or a matrix-like 'x'

Does anyone know a fix for this problem?


Solution

  • If you experiment with a small matrix you can see what is going on more easily:

    mat=matrix(1:12, 3,4)
    
    lapply(1:nrow(mat), function(y) cov(mat[1:y,]))
    
    Error in cov(mat[1:y, ]) : 
      supply both 'x' and 'y' or a matrix-like 'x'
    

    So you are getting the cov of mat[1:1,]:

    > mat[1:1,]
    [1]  1  4  7 10
    

    which suddenly isn't a matrix anymore! Which is what the error was telling you ("supply ... matrix-like 'x'"). This is because R drops dimensions when you subset a single row or column. Adjust this behaviour with drop=FALSE:

    > mat[1:1,,drop=FALSE]
         [,1] [,2] [,3] [,4]
    [1,]    1    4    7   10
    

    The column-wise covariance isn't very meaningful at this point anyway:

    > cov(mat[1:1,, drop=FALSE])
         [,1] [,2] [,3] [,4]
    [1,]   NA   NA   NA   NA
    [2,]   NA   NA   NA   NA
    [3,]   NA   NA   NA   NA
    [4,]   NA   NA   NA   NA
    

    but it at least exists...