Search code examples
rdata-structureseigenvector

How to adjust this data structure for eigen in R?


I have a list of corr matrices [1:1505, 1:1505]. I am thinking how to adjust them for the Eigen in R. The initial thread How to adjust this data structure for smaller segments in R? consisted only one test function cor which was not sufficient in the end, so here the second test function - Eigen of the cor matrix

# https://stackoverflow.com/q/40429343/54964
set.seed(24)
A=541650
m1 <- matrix(1:A, ncol=4, nrow=A)

a=360; b=1505; c=4;
m2 <- array(`length<-`(m1, a*b*c), dim = c(a,b,c))

res <- lapply(seq(dim(m2)[3]), function(i) cor(m2[,,i]))

res2 <- lapply(res, function(x) eigen(replace(x, is.na(x), 0))$vectors[,1:2])

str(res2)

e1 <- res[,1]
e2 <- res[,2]

Output

List of 4
 $ : num [1:1505, 1:2] -0.0144 0.0512 0.0157 -0.0232 0.0248 ...
 $ : num [1:1505, 1:2] 0.02233 0.00977 -0.02361 0.01597 0.00115 ...
 $ : num [1:1505, 1:2] -0.005876 0.000417 0.008206 0.006237 0.01514 ...
 $ : num [1:1505, 1:2] 0.00844 0.04382 0.0203 0.0348 0.02553 ...
Error in res2[, 1] : incorrect number of dimensions
Execution halted

R: 3.3.1
OS: Debian 8.5


Solution

  • I think the complete functional code is the following based in akrun's initial answer, his comment and some iterations

    # http://stackoverflow.com/q/40429343/54964
    set.seed(24)
    A=541650
    m1 <- matrix(1:A, ncol=4, nrow=A)
    
    a=360; b=1505; c=4;
    # http://stackoverflow.com/a/40430229/54964
    m2 <- array(`length<-`(m1, a*b*c), dim = c(a,b,c))
    
    res <- lapply(seq(dim(m2)[3]), function(i) cor(m2[,,i]))
    
    res2 <- lapply(res, function(x) eigen(replace(x, is.na(x), 0))$vectors[,1:2])
    
    str(res2)
    
    e1 <- res[1]
    e2 <- res[2]
    
    str(e1)
    
    str(e2)
    

    Output

    List of 4
     $ : num [1:1505, 1:2] -0.0258 -0.0258 -0.0258 -0.0258 -0.0258 ...
     $ : num [1:1505, 1:2] -0.0258 -0.0258 -0.0258 -0.0258 -0.0258 ...
     $ : num [1:1505, 1:2] -0.0258 -0.0258 -0.0258 -0.0258 -0.0258 ...
     $ : num [1:1505, 1:2] -0.0258 -0.0258 -0.0258 -0.0258 -0.0258 ...
    List of 1
     $ : num [1:1505, 1:1505] 1 1 1 1 1 1 1 1 1 1 ...
    List of 1
     $ : num [1:1505, 1:1505] 1 1 1 1 1 1 1 1 1 1 ...