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

一笑奈何 提交于 2020-01-04 06:35:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!