Search code examples
rlistapplylapplysapply

How to slide on the length of elements in a list() in R?


Suppose I have a list like this in R:

L <- list(
  c(0.68, 0.78, 0.63, 0.2, 0.89, 0.81),
  c(0.93, 0.89, 0.77, 0.86, 0.49, 0.2),
  c(0.88, 0.08, 0.15, 0.35, 0.6, 0.45),
  c(0.07, 0.85, 0.49, 0.92, 0.87, 0.34)
)

L
[[1]]
[1] 0.68 0.78 0.63 0.20 0.89 0.81

[[2]]
[1] 0.93 0.89 0.77 0.86 0.49 0.20

[[3]]
[1] 0.88 0.08 0.15 0.35 0.60 0.45

[[4]]
[1] 0.07 0.85 0.49 0.92 0.87 0.34

And I want to find the correlation coefficient between each pair of vectors but over multiple lengths, e.g, cor(L[[i]][1:t],L[[j]][1:t]) that t changes from 2 to 6. Is there any solution to perform it with the apply family function?


Solution

  • We may use combn

    combn(L, 2, FUN = function(x) lapply(2:6, function(t) 
           cor(x[[1]][seq_len(t)], x[[2]][seq_len(t)])), simplify = FALSE)
    

    If we need a matrix output

    combn(L, 2, FUN = function(x) do.call(c, lapply(2:6, 
         function(t) cor(x[[1]][seq_len(t)], x[[2]][seq_len(t)])))) 
    

    -output

     [,1]        [,2]       [,3]        [,4]        [,5]       [,6]
    [1,] -1.0000000 -1.00000000  1.0000000  1.00000000 -1.00000000 -1.0000000
    [2,]  0.5765567 -0.26596468  0.6204701  0.63428533 -0.28302468 -0.9210074
    [3,]  0.1641508 -0.03795219 -0.4358611  0.63452989 -0.24528496 -0.7680795
    [4,] -0.4623420  0.14114454 -0.1512739 -0.09921710 -0.41171957 -0.5675466
    [5,] -0.4846004  0.15007699 -0.2377249 -0.09824801  0.08412466 -0.5485821