【问题标题】:Plot the intersection in every two list elements绘制每两个列表元素的交集
【发布时间】:2016-04-13 16:48:18
【问题描述】:

给定一个包含 16 个元素的列表,其中每个元素都是一个命名的数字向量,我想绘制每 2 个元素之间名称交集的长度。那是;元素 1 与元素 2 的交集,元素 3 与元素 4 的交集,等等。

虽然我可以用一种非常乏味、低吞吐量的方式来完成这项工作,但我必须重复这种分析,所以我想要一种更程序化的方式来做这件事。

例如,前 2 个列表元素的前 5 个条目是:

topGenes[[1]][1:5]

3398   284353   219293     7450    54658 
2.856363 2.654106 2.653845 2.635599 2.626518 

topGenes[[2]][1:5]
1300    64581     2566     5026   146433 
2.932803 2.807381 2.790484 2.739735 2.705030 

在这里,第一行数字是基因 ID,我想知道每对向量(一个处理重复)有多少共同点,例如前 100 个。

我已尝试以下列方式使用 lapply():

vectorOfIntersectLengths <- lapply(topGenes, function(x) lapply(topGenes, function(y) length(intersect(names(x)[1:100],names(y)[1:100]))))

这似乎只对前两个元素起作用;顶级基因[[1]] & 顶级基因[[2]]。

我也一直在尝试使用 for() 循环来执行此操作,但我不确定如何编写。类似这样的东西:

lengths <- c()
for(i in 1:length(topGenes)){
  lens[i] <- length(intersect(names(topGenes[[i]][1:200]),
names(topGenes[[i+1]][1:200])))
}

这会返回一个“下标越界”错误,我不太明白。

非常感谢您的帮助!

【问题讨论】:

  • 也许可以看到?expand.grid,但我不太确定你在问什么。请您提供dput(topGenes) 或有代表性的示例子集吗?
  • 当然。以下是前 2 个列表元素的前 10 个条目:
  • 抱歉,太早按回车键了。为了(希望)清晰起见,我已经编辑了帖子。
  • 啊,你想要名称的交集——让我编辑解决方案以反映这一点。

标签: r list set-intersection


【解决方案1】:

这就是你要找的吗?

# make some fake data
set.seed(123)
some_list <- lapply(1:16, function(x) {
  y <- rexp(100)
  names(y) <- sample.int(1000,100)
  y
})

# identify all possible pairs
pairs <- t( combn(length(some_list), 2) )
# note: you could also use:  pairs <- expand.grid(1:length(some_list),1:length(some_list))
# but in addition to a-to-b, you'd get b-to-a, a-to-a, and b-to-b

# get the intersection of names of a pair of elements with given indices kept for bookkeeping
get_intersection <- function(a,b) {
  list(a = a, b = b, 
       intersection = intersect( names(some_list[[a]]), names(some_list[[b]]) ) 
  )
}

# get intersection for each pair
intersections <- mapply(get_intersection, a = pairs[,1], b = pairs[,2], SIMPLIFY=FALSE)

# print the intersections
for(indx in 1:length(intersections)){
  writeLines(paste('Intersection of', intersections[[indx]]$a, 'and',
                   intersections[[indx]]$b, 'contains:', 
                   paste( sort(intersections[[indx]]$intersection), collapse=', ') ) )
}

【讨论】:

  • 几乎!我可以看到结果向量中的相交长度以及自相交。
  • 确实如此。输出看起来有点滑稽,但我正在寻找的相交元素的名称肯定在那里。当我运行代码时,输​​出,交叉点,看起来像这样:
  • 256 个 $ 列表:3 个列表 ..$ a :int 1 ..$ b :int 1 ..$ 交集:chr [1:100] "3398" "284353" "219293" "7450" ... $ :List of 3 ..$ a : int 2 ..$ b : int 1 ..$ intersection: chr [1:3] "121260" "3934" "29890" 最后一行显示topGenes 的前 2 个列表元素的名称中的交集,我猜长度为 100 的第一个交集是其自身的第一个元素。虽然有效! :-)
  • @Forest 我用打印例程将答案更新到控制台。通过将con= 参数更改为writeLines,您可以轻松地将其打印到文件a。这是一个不规则的表格,因此 XML 或 JSON 可能是表示它的好方法,但如果您只是手动使用它,您可以将输出复制或通过管道传输到适合您的任何内容。
猜你喜欢
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 2020-03-16
  • 2020-11-23
  • 2011-09-02
相关资源
最近更新 更多