在 R 中创建边列表
Creating edge list in R
我有这样的数据:
ID=c(rep("ID1",3), rep("ID2",2), "ID3", rep("ID4",2))
item=c("a","b","c","a","c","a","b","a")
data.frame(ID,item)
ID1 a
ID1 b
ID1 c
ID2 a
ID2 c
ID3 a
ID4 b
ID4 a
我需要它作为这样的边列表:
a;b
b;c
a;c
a;c
b;a
前三个边来自 ID1,第四个边来自 ID2,ID3 没有边所以没有边,第五个边来自 ID4。关于如何实现这一目标的任何想法? melt/cast?
尝试
res <- do.call(rbind,with(df, tapply(item, ID,
FUN=function(x) if(length(x)>=2) t(combn(x,2)))))
paste(res[,1], res[,2], sep=";")
#[1] "a;b" "a;c" "b;c" "a;c" "b;a"
我想应该有一个简单的 igrpah
解决方案,但这里有一个使用 data.table
包
的简单解决方案
library(data.table)
setDT(df)[, if(.N > 1) combn(as.character(item), 2, paste, collapse = ";"), ID]
# ID V1
# 1: ID1 a;b
# 2: ID1 a;c
# 3: ID1 b;c
# 4: ID2 a;c
# 5: ID4 b;a
这是一个更具扩展性的解决方案,它使用与其他解决方案相同的核心逻辑:
library(plyr)
library(dplyr)
ID=c(rep("ID1",3), rep("ID2",2), "ID3", rep("ID4",2))
item=c("a","b","c","a","c","a","b","a")
dfPaths = data.frame(ID, item)
dfPaths2 = dfPaths %>%
group_by(ID) %>%
mutate(numitems = n(), item = as.character(item)) %>%
filter(numitems > 1)
ddply(dfPaths2, .(ID), function(x) t(combn(x$item, 2)))
我有这样的数据:
ID=c(rep("ID1",3), rep("ID2",2), "ID3", rep("ID4",2))
item=c("a","b","c","a","c","a","b","a")
data.frame(ID,item)
ID1 a
ID1 b
ID1 c
ID2 a
ID2 c
ID3 a
ID4 b
ID4 a
我需要它作为这样的边列表:
a;b
b;c
a;c
a;c
b;a
前三个边来自 ID1,第四个边来自 ID2,ID3 没有边所以没有边,第五个边来自 ID4。关于如何实现这一目标的任何想法? melt/cast?
尝试
res <- do.call(rbind,with(df, tapply(item, ID,
FUN=function(x) if(length(x)>=2) t(combn(x,2)))))
paste(res[,1], res[,2], sep=";")
#[1] "a;b" "a;c" "b;c" "a;c" "b;a"
我想应该有一个简单的 igrpah
解决方案,但这里有一个使用 data.table
包
library(data.table)
setDT(df)[, if(.N > 1) combn(as.character(item), 2, paste, collapse = ";"), ID]
# ID V1
# 1: ID1 a;b
# 2: ID1 a;c
# 3: ID1 b;c
# 4: ID2 a;c
# 5: ID4 b;a
这是一个更具扩展性的解决方案,它使用与其他解决方案相同的核心逻辑:
library(plyr)
library(dplyr)
ID=c(rep("ID1",3), rep("ID2",2), "ID3", rep("ID4",2))
item=c("a","b","c","a","c","a","b","a")
dfPaths = data.frame(ID, item)
dfPaths2 = dfPaths %>%
group_by(ID) %>%
mutate(numitems = n(), item = as.character(item)) %>%
filter(numitems > 1)
ddply(dfPaths2, .(ID), function(x) t(combn(x$item, 2)))