5

我有这样的数据:

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。关于如何做到这一点的任何想法?熔化/铸造?

4

3 回答 3

8

我猜应该有一个简单的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
于 2015-02-08T12:19:45.330 回答
3

尝试

 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"
于 2015-02-08T12:07:08.723 回答
2

这是一个更具可扩展性的解决方案,它使用与其他解决方案相同的核心逻辑:

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)))
于 2015-02-08T13:10:43.237 回答