r - 将值列表转换为每个值的列表索引列表

标签 r

我有一个包含 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))

我想为“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)...) 

如何为任何“cats.list”创建这样的索引列表?

最佳答案

1) reshape2 使用reshape2中的meltcats.list转换成第一列value为元素,第二列L1为{17945}对应的组件编号的数据框该元素所属。然后 cats.list 使用指定的公式。

library(reshape2)

unstack(melt(cats.list), L1 ~ value)

给予:
$`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

2) 拆分 我们也可以在没有任何包的情况下这样做。 unstack 等于 (1) 中的 rep(seq_along(L), L)m$L1 等于 (1) 中的 unlist(cats.list)
L <- lengths(cats.list)
split(rep(seq_along(L), L), unlist(cats.list))

3) stack/unstack 如果我们命名 m$value 组件,我们也可以仅使用基本 R 和 stack/unstack 来执行此操作。
cats.named <- setNames(cats.list, seq_along(cats.list))
unstack(stack(cats.named), ind ~ values)

笔记

我们可以将其绘制为二部图,如下所示:
library(igraph)
library(reshape2)

m <- melt(cats.list)
M <- table(m)
g <- graph_from_incidence_matrix(M)
plot(g, layout = layout_as_bipartite)

screenshot

关于r - 将值列表转换为每个值的列表索引列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53461430/

相关文章:

r - 转换 Dataframe 以在 ggplot2 中制作瀑布图

R Shiny : Keep/retain values of reactive inputs after modifying selection

r - 如何从你的测试输出对象中提取各种统计数据,如 teststat 和 pvalue 等

r - 团体票吗?

在返回多行 R 的每一行上运行函数

r - dplyr :mutate and transform when using pmin and pmax? 之间的差异

r - R绘制所有轴标签(防止被跳过)

r - 将向量转换为列表,向量中的每个元素作为列表中的元素

r - ggplot 直方图作为特定组的百分比

r - 根据r中的多列查找数据框中的重复行