[英]apply outer() on two lists
I have a list, say exm = list( elm1=c('a', 'b'), elm2=c('b', 'c', 'd'), elm3=c('b', 'c', 'd', 'e'))
. 我有一个列表,比如
exm = list( elm1=c('a', 'b'), elm2=c('b', 'c', 'd'), elm3=c('b', 'c', 'd', 'e'))
。 I want to apply a function on every combination of two elements from exm
, eg, length( intersect( exm$elm1, exm$elm2 ) )
. 我想对
exm
中两个元素的每个组合应用一个函数,例如length( intersect( exm$elm1, exm$elm2 ) )
。 The result should be a symmetric matrix. 结果应该是对称矩阵。 The function
outer
seems to do this job, but it works only for vector, not list. 函数
outer
似乎完成这项工作,但它只适用于矢量,而不是列表。 Any idea to do this? 有没有想过这样做?
How about the following: 以下内容如何:
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
Here is another approach: 这是另一种方法:
# Data
exm = list( elm1=c('a', 'b'), elm2=c('b', 'c', 'd'), elm3=c('b', 'c', 'd', 'e'))
# Set up possible comparisons
combinations <- data.frame(t(combn(names(exm), 2)))
# Caculate overlap
for (i in 1:nrow(combinations)){
combinations$length[[i]] <- length(intersect(exm[[combinations[i,1]]], exm[[combinations[i,2]]]))
}
# > combinations
# X1 X2 length
# 1 elm1 elm2 1
# 2 elm1 elm3 1
# 3 elm2 elm3 3
# Matrix output
m.out <- matrix(ncol=length(exm), nrow=length(exm), dimnames = list(names(exm),names(exm)))
# Fil in overlap figures
m.out[cbind(combinations$X1, combinations$X2)] <- combinations$length
m.out[cbind(combinations$X2, combinations$X1)] <- combinations$length
# Fill in length of vector itself as diagonal - if necessary
diag(m.out) <- unlist(lapply(exm, length))
# > m.out
# elm1 elm2 elm3
# elm1 2 1 1
# elm2 1 3 3
# elm3 1 3 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.