我想从匹配表中的列值创建一条边,所以基本上:
V1 V2 V3
A 1 1 0
B 1 0 1
C 0 1 1
D 1 0 1
如果我有一张这样的桌子,那么我想制作一个边缘列表,其中
A - B
A - D
A - C
B - C
B - D
所以我想在每行的列值匹配时创建一条边。我查看了很多文档,但我似乎无法找出任何与此类似的东西。任何帮助,将不胜感激!
我想从匹配表中的列值创建一条边,所以基本上:
V1 V2 V3
A 1 1 0
B 1 0 1
C 0 1 1
D 1 0 1
如果我有一张这样的桌子,那么我想制作一个边缘列表,其中
A - B
A - D
A - C
B - C
B - D
所以我想在每行的列值匹配时创建一条边。我查看了很多文档,但我似乎无法找出任何与此类似的东西。任何帮助,将不胜感激!
crossprod
在您的数据上使用后,我会尝试“igraph”包。假设你data.frame
被称为“mydf”:
out <- crossprod(t(mydf))
out[lower.tri(out, diag=TRUE)] <- 0
library(igraph)
g <- graph.adjacency(out)
get.edgelist(g)
# [,1] [,2]
# [1,] "A" "B"
# [2,] "A" "C"
# [3,] "A" "D"
# [4,] "B" "C"
# [5,] "B" "D"
# [6,] "B" "D"
# [7,] "C" "D"
如果你不想重复,你可以使用:
g <- graph.adjacency(out > 0)
get.edgelist(g)
试试这个:
#dummy data
df <- read.table(text="
A 1 1 0
B 1 0 1
C 0 1 1
D 1 0 1",sep=" ", as.is=TRUE)
#get names where 1 per column
lst <- sapply(2:ncol(df), function(j)
df[df[,j]==1,1])
#make combinations
lst_comb <- sapply(1:(ncol(df)-1), function(i)
combn(lst[[i]],2))
#output
matrix(sort(unique(
unlist(
sapply(1:length(lst_comb),function(i){
x <- t(lst_comb[[i]])
paste0(x[,1],"-",x[,2])
})))))
# [,1]
#[1,] "A-B"
#[2,] "A-C"
#[3,] "A-D"
#[4,] "B-C"
#[5,] "B-D"
#[6,] "C-D"
这是我的方法基于combn
:
sort(unique(unlist(apply(df, 2, function(x)combn(rownames(df)[which(x==1)], 2, FUN=paste, collapse=" - ")))))
随着df
您的数据,为您提供:
[1] "A - B" "A - C" "A - D" "B - C" "B - D" "C - D"
dat<- read.table(text=" ID V1 V2 V3
A 1 1 0
B 1 0 1
C 0 1 1
D 1 0 1", header= TRUE)
library(reshape2)
library(tnet)
dat2 <- melt(dat, id= "ID")
dat2 <- dat2[dat2$value > 0 ,]
dat3 <- as.tnet(cbind(dat2[,1],dat2[,2]), type="binary two-mode tnet")
dat3 <- projecting_tm(dat3, method = "sum")[1:2]
dat3[dat3 == 1] <- "A" # there is an easier way to change names
dat3[dat3 == 2] <- "B"
dat3[dat3 == 3] <- "C"
dat3[dat3 == 4] <- "D"
dat3[!duplicated(t(apply(dat3, 1, sort))), ]
# i j
#1 A B
#2 A C
#3 A D
#5 B C
#6 B D
#9 C D