我有一个列表,其元素是整数,如果这些元素至少共享一个值,我想累积这些元素。对于那些与其他元素不共享任何值(value)观的元素,我希望它们保持原样。这是我的 sample 日期:
x <- list(c(1, 2), c(1, 2, 3), c(2, 3, 4), c(3, 4, 5), c(4, 5, 8), c(6, 9, 7), 7, c(5, 8), 10, 11)
这是我想要的输出:desired_reult <- list(c(1, 2, 3, 4, 5, 8),
c(6, 9, 7),
10,
11)
我想先用 reduce
或 accumulate
来自 purrr
的函数但任何其他 tidyverse
解决方案将受到欢迎。到目前为止我已经尝试过这个解决方案,但它只给了我一个 union
并且显然放弃了其余部分:x %>%
reduce(~ if(any(.x %in% .y)) union(.x, .y) else .x)
[1] 1 2 3 4 5 8
一般来说,我正在寻找一种将整数 (id) 与常见值(如某种聚类)进行分组的方法,但不幸的是,到目前为止,我的努力都是徒劳的。非常感谢您提前提供帮助。
最佳答案
一种方法:
i 与 j 相邻且仅当 intersect(i, j) != 空集。我们想找到矩阵的连通分量,在位置 (i,j) 上有 1 个当条件是集合 i 与集合 j 相邻,否则为 0。前 4 行构建邻接矩阵,第 5 行和第 6 行找到连接的组件,其余部分基于该成员资格拆分列表并采用唯一值。
library(tidyverse)
library(igraph)
map(x, function(a) map_int(x, ~length(base::intersect(a, .x)) > 0) * 1L) %>%
reduce(rbind) %>%
graph.adjacency() %>%
as.undirected() %>%
components() %>%
pluck("membership") %>%
split(seq_along(.), .) %>%
map(~unique(unlist(x[.x])))
关于r - 基于至少一个共同值对 Id 进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67970817/