【问题标题】:How to slide on the length of elements in a list() in R?如何在 R 中的 list() 中滑动元素的长度?
【发布时间】:2021-08-20 03:05:20
【问题描述】:

假设我在 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

我想找到每对向量之间的相关系数,但在多个长度上,例如,cor(L[[i]][1:t],L[[j]][1:t]) t2 to 6 变化。有没有办法用applyfamily 函数来执行它?

【问题讨论】:

    标签: r list apply lapply sapply


    【解决方案1】:

    我们可能会使用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)
    

    如果我们需要matrix 输出

    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)])))) 
    

    -输出

     [,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
    

    【讨论】:

    • 您可以像combn(L, 2, FUN=function(x) { sapply(2:6, function(y) cor(head(x[[1]], y), head(x[[2]],y))) }) 我认为的那样更简单地获取矩阵。基本上只是将lapply 更改为sapply
    【解决方案2】:

    另一种方式可以是:

    a <- sequence(2:6)
    b <- cumsum(a==1)
    d <- data.frame(L)
    e <- lower.tri(diag(length(L)))
    do.call(rbind, by(d[a,], b, function(x)cor(x)[e]))
    
            [,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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 2020-02-10
      • 2016-04-06
      • 1970-01-01
      • 2014-06-02
      相关资源
      最近更新 更多