我有一个清单,说exm = list( elm1=c('a', 'b'), elm2=c('b', 'c', 'd'), elm3=c('b', 'c', 'd', 'e'))
。我想对以下两个元素的每个组合应用一个函数exm
, e.g., length( intersect( exm$elm1, exm$elm2 ) )
。结果应该是一个对称矩阵。功能outer
似乎可以完成这项工作,但它仅适用于矢量,不适用于列表。有想法这样做吗?
怎么样:
exm = list( elm1=c('a', 'b'), elm2=c('b', 'c', 'd'), elm3=c('b', 'c', 'd', 'e'))
#Use mapply to vectorise your function
int2 <- function(x,y) mapply(function(x,y) {length( intersect( x, y ) )},
exm[x], exm[y])
#Use outer on the indices of exm, rather than exm itself
s <- seq_along(exm)
outer(s,s,int2)
# [,1] [,2] [,3]
# [1,] 2 1 1
# [2,] 1 3 3
# [3,] 1 3 4
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)