【发布时间】:2016-05-02 03:23:25
【问题描述】:
我想对列表元素的所有成对组合应用一个函数。
每个元素都是一个长度相同的向量。我想要n x n 矩阵格式的输出,n 是我列表中元素的数量。
考虑以下示例:
# Generating data
l <- list()
for(i in 1:5) l[[i]] <- sample(0:9, 5, T)
# Function to apply
foo <- function(x, y) 1 - sum(x * y) / sqrt(sum(x ^ 2) * sum(y ^ 2))
# Generating combinations
comb <- expand.grid(x = 1:5, y = 1:5)
此循环有效,但速度慢,输出未格式化为矩阵
# Applying function
out <- list()
for(i in 1:nrow(comb)) {
out[[i]] <- foo(l[[comb[i, 'x']]], l[[comb[i, 'y']]])
}
有什么想法吗?
【问题讨论】:
-
outer(l,l,Vectorize(foo))
标签: r list function combinations