我有一个包含6个元素的'cats.list'列表.有9个唯一的整数是一个或多个元素的成员.例如
cats.list <- list(c(1, 2, 6), c(1, 8, 9), c(3, 4, 5, 7),
c(3, 6, 7), c(1, 3, 7, 8, 9), c(4, 5, 9))
Run Code Online (Sandbox Code Playgroud)
我想为'cats.list'中的9个整数中的每个整数创建一个包含一个元素的列表.新列表中的每个元素都应包含给定整数的'cat.list'中的列表索引.
例如,1出现在'cat.list'中的列表元素1,2,5中.2仅出现在元素1中.3出现在元素3,4,5中.因此新列表中的前三个元素将是:
el.list <- list(c(1, 2, 5), 1, c(3, 4, 5)...)
Run Code Online (Sandbox Code Playgroud)
如何为任何'cats.list'创建这样的索引列表?
使用 -
cats.list <- list(c(1, 2, 6), c(1, 8, 9), c(3, 4, 5, 7), c(3, 6, 7),
c(1, 3, 7, 8, 9), c(4, 5, 9))
output <- c()
for(i in sort(unique(unlist(cats.list)))){
output <- c(output, list(grep(i,cats.list)))
}
Run Code Online (Sandbox Code Playgroud)
产量
[[1]]
[1] 1 2 5
[[2]]
[1] 1
[[3]]
[1] 3 4 5
[[4]]
[1] 3 6
[[5]]
[1] 3 6
[[6]]
[1] 1 4
[[7]]
[1] 3 4 5
[[8]]
[1] 2 5
[[9]]
[1] 2 5 6
Run Code Online (Sandbox Code Playgroud)
说明
unlist(cats.list)展平现有列表,将其包装unique并sort创建搜索列表,您可以使用该列表迭代搜索
神奇之处在于grep(i,cats.list),它可以为每次搜索提供您想要的东西.
将它们放在一个output列表中是微不足道的.希望有所帮助!
编辑
感谢@ G. Grothendieck,这可以缩短为 -
output <- lapply(sort(unique(unlist(cats.list))), grep, cats.list)
Run Code Online (Sandbox Code Playgroud)
1)reshape2melt在reshape2中使用转换cats.list为数据框,其第一列value是元素,第二列L1是该cats.list元素所属的相应组件编号.然后unstack用指定的公式.
library(reshape2)
unstack(melt(cats.list), L1 ~ value)
Run Code Online (Sandbox Code Playgroud)
赠送:
$`1`
[1] 1 2 5
$`2`
[1] 1
$`3`
[1] 3 4 5
$`4`
[1] 3 6
$`5`
[1] 3 6
$`6`
[1] 1 4
$`7`
[1] 3 4 5
$`8`
[1] 2 5
$`9`
[1] 2 5 6
Run Code Online (Sandbox Code Playgroud)
2)拆分我们也可以这样做,没有任何包. rep(seq_along(L), L)等于m$L1(1)和unlist(cats.list)等于m$value(1).
L <- lengths(cats.list)
split(rep(seq_along(L), L), unlist(cats.list))
Run Code Online (Sandbox Code Playgroud)
3)stack/unstack如果我们命名cats.list组件,我们也可以只使用base R和stack/unstack .
cats.named <- setNames(cats.list, seq_along(cats.list))
unstack(stack(cats.named), ind ~ values)
Run Code Online (Sandbox Code Playgroud)
我们可以将其绘制为这样的二分图:
library(igraph)
library(reshape2)
m <- melt(cats.list)
M <- table(m)
g <- graph_from_incidence_matrix(M)
plot(g, layout = layout_as_bipartite)
Run Code Online (Sandbox Code Playgroud)