将函数应用于向量列表的所有组合-R [英] Apply a function over all combinations of a list of vectors -R
本文介绍了将函数应用于向量列表的所有组合-R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个向量列表,我需要将一个函数应用于所有可能的组合并将结果表示为矩阵,我可以使用在r中效率低下的 for
循环来做到这一点,可以有人指出其他方法可以做到这一点,例如使用Apply等吗?
I have a list of vectors and I need to apply a function to all possible combinations and express the result in a matrix, I can do that using a for
loop which is inefficient in r, can anybody point out any other ways to do it, e.g using apply etc?
代码例如
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的矩阵.
I need to apply add_function to all possible combinations and get a 3 x 3 matrix.
推荐答案
我们可以使用外部
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
这篇关于将函数应用于向量列表的所有组合-R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文