这是我昨天提出的一个问题的后续,现在扩展到包括 2 个以上的输入。我能够在 SO 上找到两个 相关的答案,但没有一个提供足够的信息让我以高效的方式解决这个问题。
我想将 IRanges 列表组合成一个 IRanges。这是一个示例输入:
[[1]]
IRanges object with 2 ranges and 1 metadata column:
start end width | on_betalac
<integer> <integer> <integer> | <logical>
[1] 1 21 21 | FALSE
[2] 22 22 1 | TRUE
[[2]]
IRanges object with 2 ranges and 1 metadata column:
start end width | on_other
<integer> <integer> <integer> | <logical>
[1] 1 21 21 | FALSE
[2] 22 22 1 | TRUE
[[3]]
IRanges object with 1 range and 1 metadata column:
start end width | on_pen
<integer> <integer> <integer> | <logical>
[1] 1 22 22 | FALSE
[[4]]
IRanges object with 3 ranges and 1 metadata column:
start end width | on_quin
<integer> <integer> <integer> | <logical>
[1] 1 3 3 | FALSE
[2] 4 13 10 | TRUE
[3] 14 22 9 | FALSE
为了便于复制,dput
此列表位于我的帖子末尾。
我想要的输出是:
IRanges object with 4 ranges and 4 metadata columns:
start end width | on_betalac on_other on_pen on_quin
<integer> <integer> <integer> | <logical> <logical> <logical> <logical>
[1] 1 3 3 | FALSE FALSE FALSE FALSE
[2] 4 13 10 | FALSE FALSE FALSE TRUE
[3] 14 21 8 | FALSE FALSE FALSE FALSE
[4] 22 22 1 | TRUE TRUE FALSE FALSE
您可以看到输出有点像输入的分离,但是 mcols 传播通过,因此每个输出行都有输入行的 mcols “引起”它。
这是我的解决方案,它有效,但速度很慢。
combine_exposures <- function(exposures) {
cd <- do.call(what = c, args = exposures)
mc <- mcols(cd)
dj <- disjoin(x = cd, with.revmap = TRUE)
r <- mcols(dj)$revmap
d <- as.data.frame(matrix(nrow = length(dj), ncol = ncol(mc)))
names(d) <- names(mc)
for (i in 1:length(dj)) {
d[i,] <- sapply(X = 1:ncol(mc), FUN = function(j) { mc[r[[i]][j], j] })
}
mcols(dj) <- d
return(dj)
}
这是示例输入的 dput:
list(new("IRanges", start = c(1L, 22L), width = c(21L, 1L), NAMES = NULL,
elementType = "ANY", elementMetadata = new("DataFrame", rownames = NULL,
nrows = 2L, listData = list(on_betalac = c(FALSE, TRUE
)), elementType = "ANY", elementMetadata = NULL, metadata = list()),
metadata = list()), new("IRanges", start = c(1L, 22L), width = c(21L,
1L), NAMES = NULL, elementType = "ANY", elementMetadata = new("DataFrame",
rownames = NULL, nrows = 2L, listData = list(on_other = c(FALSE,
TRUE)), elementType = "ANY", elementMetadata = NULL, metadata = list()),
metadata = list()), new("IRanges", start = 1L, width = 22L,
NAMES = NULL, elementType = "ANY", elementMetadata = new("DataFrame",
rownames = NULL, nrows = 1L, listData = list(on_pen = FALSE),
elementType = "ANY", elementMetadata = NULL, metadata = list()),
metadata = list()), new("IRanges", start = c(1L, 4L, 14L),
width = c(3L, 10L, 9L), NAMES = NULL, elementType = "ANY",
elementMetadata = new("DataFrame", rownames = NULL, nrows = 3L,
listData = list(on_quin = c(FALSE, TRUE, FALSE)), elementType = "ANY",
elementMetadata = NULL, metadata = list()), metadata = list()))