是否有一种更快(易于扩展)和更清洁的方法来从 x 获取 y?
x <- list(c("a", "b", "c", "d"),
c("a", "b", "e"),
c("x", "y"),
c("z", "x"))
y <- vector(mode = "list", length = length(x))
for(i in 1:length(x)){
for(j in 1:length(x)){
y[[i]] <- append(y[[i]], length(intersect(x[[i]], x[[j]])))}}
y <- do.call(rbind, y)
最佳答案
un <- unique(unlist(x))
crossprod(sapply(x,function(y)un%in%y))
# [,1] [,2] [,3] [,4]
# [1,] 4 2 0 0
# [2,] 2 3 0 0
# [3,] 0 0 2 1
# [4,] 0 0 1 2
microbenchmark::microbenchmark(user1389960(), times = 1000)
# Unit: microseconds
# expr min lq mean median uq max neval
# user1389960() 172.631 181.5195 243.918 187.1015 198.716 45083.95 1000
microbenchmark::microbenchmark(eipi10(), times = 1000)
# Unit: microseconds
# expr min lq mean median uq max neval
# eipi10() 218.625 225.9635 246.9797 234.469 245.4545 1175.439 1000
microbenchmark::microbenchmark(Julius(), times = 1000)
# Unit: microseconds
# expr min lq mean median uq max neval
# Julius() 30.322 32.511 37.61541 34.0175 37.957 1026.268 1000
microbenchmark::microbenchmark(ColonelBeauvel(), times = 1000)
# Unit: microseconds
# expr min lq mean median uq max neval
# ColonelBeauvel() 162.103 169.548 183.9076 175.683 183.677 1052.435 1000
关于r - 查找列表元素交集的长度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29421774/