【问题标题】:How to combine subsequent list elements into a new list in R?如何将后续列表元素组合成R中的新列表?
【发布时间】:2013-01-21 23:23:53
【问题描述】:

例如:我有一个矩阵列表,我想评估它们的差异,类似于 3-D 差异。所以如果我有:

m1 <- matrix(1:4, ncol=2)
m2 <- matrix(5:8, ncol=2)
m3 <- matrix(9:12, ncol=2)
mat.list <- list(m1,m2,m3)

我要获得

mat.diff <- list(m2-m1, m3-m2)

我找到的解决方法如下:

mat.diff <- mapply(function (A,B) B-A, mat.list[-length(mat.list)], mat.list[-1])

有没有更好的/内置的方法来做到这一点?

【问题讨论】:

  • 如果能用一个(小)可重现的例子来解释这一点会很好。
  • 我读懂了你的想法并编辑了问题:)
  • @piccobello,这仍然无法重现。无需尝试,我保证会出现X1 not found 类型的错误。
  • 好的,谢谢 Arun 的例子!
  • 我将@Arun 的示例合并到问题中。再次感谢!

标签: r list functional-programming


【解决方案1】:

您可以只使用lapply 或其他循环方式来做到这一点:

mat.diff <- lapply( tail( seq_along(mat.list), -1 ), 
                    function(i) mat.list[[i]] - mat.list[[ i-1 ]] )

【讨论】:

  • 到目前为止我最喜欢的,但是我会使用更易读的 lapply(2:length(mat.list),...),就像@Arun 的回答一样。有更好的吗?
  • 使用seq_along 更好,因为它可以处理类似于length(mat.list) &lt; 2 的情况的差异。在这种情况下,2:length(mat.list) 将产生 2:1,而 seq_along(mat.list) 将产生 1 并且不会导致错误/错误结果。
  • 另外,你的意思是什么更好?你希望什么??
  • magic.function
  • 谢谢格雷格!我的意思是问是否有一个行为类似于 magic.function 的本机 R 函数。感谢大家的想法!
【解决方案2】:

您可以使用combn 生成矩阵的索引并对每个组合应用一个函数。

       combn(1:length(l),2,FUN=function(x) 
            if(diff(x) == 1)         ## apply just for consecutive index 
                  l[[x[2]]]-l[[x[1]]], 
                  simplify = FALSE)  ## to get a list 

使用@Arun 数据,我得到:

[[1]]
     [,1] [,2]
[1,]    4    4
[2,]    4    4

[[2]]
NULL

[[3]]
     [,1] [,2]
[1,]    4    4
[2,]    4    4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-16
    • 2021-05-17
    • 2021-05-24
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多