问题
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?
code e.g.
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)
}
I need to apply add_function to all possible combinations and get a 3 x 3 matrix.
回答1:
We can use 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
来源:https://stackoverflow.com/questions/33856920/apply-a-function-over-all-combinations-of-a-list-of-vectors-r