我觉得好像在问错误的问题,并试图重新发明轮子.我错过了什么?
我有一堆值,比方说8,我需要互相测试.我已经构建了一个函数,该函数返回一个矩阵,说明是否有任何两个值都在一个组中.由于缺乏更好的想法,让我在这里粘贴输出:
data.text <-
"1 2 3 4 5 6 7 8
1 TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE
2 TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE
3 TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE
4 FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE
5 FALSE FALSE FALSE FALSE TRUE TRUE NA FALSE
6 FALSE FALSE FALSE FALSE TRUE TRUE NA FALSE
7 FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE
8 FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE"
data <- read.table(text=data.text, header = TRUE)
data <- as.matrix(data)
colnames(data) <- 1:8
Run Code Online (Sandbox Code Playgroud)
因此,第1行表示值1与自身组(第1列),值为2和3,但值不是4 - 8.值5和6也在同一组内.
我正在尝试使用此信息来创建单个组ID以及该组中所有元素的向量:
到目前为止我做了什么:
# row and column index for all TRUE values by row
groups <- which(data,arr.ind = T)
# sort each row in acending order in order to find duplicate values
groups.sorted <- t(apply(groups,1,sort))
# drop double statments ("1 and 2", "2 and 1")
groups.unique <- unique(groups.sorted)
# drop obivous information ("1 and 1")
groups.real <- groups.unique[groups.unique[,1] != groups.unique[,2],]
Run Code Online (Sandbox Code Playgroud)
此时我被困住了.如何自动化第1,2和3行属于同一组的事实?
总而言之,我觉得我很笨拙地走这条路.任何人都能指出我更优雅的方式吗?
我会使用这个igraph包来做这类事情:
require(igraph)
components(graph_from_adjacency_matrix(data))$membership
#1 2 3 4 5 6 7 8
#1 1 1 2 3 3 4 5
Run Code Online (Sandbox Code Playgroud)
您将获得一个命名向量,其名称是元素,值是它们所属的组.