合并相交列表元素

发布于 2025-02-03 23:23:58 字数 1142 浏览 3 评论 0原文

我有一个r integer vector s的列表,某些元素是冗余的,而其他元素相互相交:

ll <- list(c(1,4), c(5,7,3,9), c(5,3,7,9), c(2,7,10), 8, 6)

Integer vector元素中的s只是索引而不是范围,列表中元素的顺序是任意的。

我正在寻找一个将返回list的函数,该函数将合并ll的相交元素并删除冗余。

对于示例ll,此功能将返回:

list(c(1,4), c(2,3,5,7,9,10), 6, 8)

有什么想法吗?

不幸的是,@Alexis_laz在这篇文章无法解决我的问题,因为它假定列表已排序,这不是我的情况。

例如,如果我更改ll的元素的顺序:

ll <- list(c(2,7,10), c(1,4), c(5,7,3,9), 8, 6, c(5,3,7,9))

@Alexis_laz的解决方案的矢量元素则无法保持。

I have a list of R integer vectors which some elements are redundant and others intersect each other:

ll <- list(c(1,4), c(5,7,3,9), c(5,3,7,9), c(2,7,10), 8, 6)

The integers in the vector elements are just indices and not ranges, and the order of the elements in the list is arbitrary.

I'm looking for a function that'll return a list that'll merge ll's intersecting elements and remove the redundancy.

For the example ll above this function will return:

list(c(1,4), c(2,3,5,7,9,10), 6, 8)

Any idea?

Unfortunately, the solution offered by @alexis_laz in this post doesn't solve my problem because it assumes that the list is ordered, which is not my case.

For example, if I change the order of ll's elements:

ll <- list(c(2,7,10), c(1,4), c(5,7,3,9), 8, 6, c(5,3,7,9))

@alexis_laz's solution doesn't hold.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不咬妳我踢妳 2025-02-10 23:23:58

这很混乱,但我为您的情况做出了工作。

library(dplyr)

for (i in 1:(length(ll)-1)){
  if (!is.null(unlist(ll[i])) & length(ll) > i){
    for (j in length(ll):(i+1)) {
      if (length(intersect(ll[[i]], ll[[j]])) > 0 ){
        ll[[i]] <- union(ll[[i]], ll[[j]])
        ll <- ll[-j]
      }
    }
  }
}

[[1]]
[1] 1 4

[[2]]
[1]  5  7  3  9  2 10

[[3]]
[1] 8

[[4]]
[1] 6

It's pretty messy but it my works for your case.

library(dplyr)

for (i in 1:(length(ll)-1)){
  if (!is.null(unlist(ll[i])) & length(ll) > i){
    for (j in length(ll):(i+1)) {
      if (length(intersect(ll[[i]], ll[[j]])) > 0 ){
        ll[[i]] <- union(ll[[i]], ll[[j]])
        ll <- ll[-j]
      }
    }
  }
}

[[1]]
[1] 1 4

[[2]]
[1]  5  7  3  9  2 10

[[3]]
[1] 8

[[4]]
[1] 6
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文