对向量列表的所有组合应用一个函数 -R

Apply a function over all combinations of a list of vectors -R

我有一个向量列表,我需要对所有可能的组合应用一个函数并用矩阵表示结果,我可以使用 for 循环来做到这一点,这在 r 中效率低下,任何人都可以指出任何其他方法,例如使用 apply 等?

代码例如

list <- list(c(1,2),c(3,4),c(5,6))

add_function <- function(x1,x2){
  g1 <- x1[1]+x2[2]
  g2 <- x1[2]+x2[1]
  return(g1*g2)
}

我需要将 add_function 应用于所有可能的组合并得到一个 3 x 3 矩阵。

我们可以使用outer

 outer(seq_along(list), seq_along(list), 
    FUN= Vectorize(function(i,j) add_function(list[[i]], list[[j]])))
 #     [,1] [,2] [,3]
 #[1,]    9   25   49
 #[2,]   25   49   81
 #[3,]   49   81  121