将函数应用于R中列表元素的所有成对组合 [英] Apply a function to all pairwise combinations of list elements in R

查看:27
本文介绍了将函数应用于R中列表元素的所有成对组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将函数应用于列表元素的所有成对组合。 每个元素都是长度相同的向量。我想要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']]])
}

有什么想法吗?

推荐答案

嵌套sApply可以实现此目的:

sapply(l, function(x) sapply(l, function(y) foo(x,y)))

我对@A.Webb的解决方案感兴趣。以下是一些基准测试:

R> for(i in 1:50) l[[i]] <- sample(0:9, 5, T)
R> microbenchmark(sapply(l, function(x) sapply(l, function(y) foo(x,y))), outer(l,l,Vectorize(foo)), time=1000)
Unit: nanoseconds
                                                    expr     min        lq
 sapply(l, function(x) sapply(l, function(y) foo(x, y))) 7493739 8479127.0
                             outer(l, l, Vectorize(foo)) 6778098 8316362.5
                                                    time       5      48.5
      mean    median        uq      max neval
 1.042e+07 1.027e+07 1.155e+07 17982289   100
 1.030e+07 1.002e+07 1.187e+07 16076063   100
 1.672e+02 1.385e+02 1.875e+02      914   100

R> for(i in 1:500) l[[i]] <- sample(0:9, 5, T)
R> microbenchmark(sapply(l, function(x) sapply(l, function(y) foo(x,y))), outer(l,l,Vectorize(foo)), times=100)
Unit: milliseconds
                                                    expr   min    lq  mean
 sapply(l, function(x) sapply(l, function(y) foo(x, y))) 677.3 768.5 820.4
                             outer(l, l, Vectorize(foo)) 828.6 903.0 958.3
 median    uq  max neval
  815.9 842.7 1278   100
  930.7 960.5 1819   100

因此,对于较小的列表,外部解决方案会更快一些,但对于较大的列表,嵌套的sApply解决方案可能会更快一些。

这篇关于将函数应用于R中列表元素的所有成对组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆