从两列映射中分组多对多关系

时间:2012-09-27 21:48:05

标签: r data.table

我有一个SQL表,可以映射作者和书籍。我想将链接的作者和书籍(由同一作者撰写的书籍和共同撰写一本书的作者)组合在一起,并确定这些群体的大小。例如,如果J.K. Rowling与Junot Diaz合作,而Junot Diaz与Zadie Smith共同撰写了一本书,然后我希望所有三位作者都在同一组中。

这是一个玩具数据集(h / t Matthew Dowle),其中包含我正在讨论的一些关系:

set.seed(1)
authors <- replicate(100,sample(1:3,1))
book_id <- rep(1:100,times=authors)
author_id <- c(lapply(authors,sample,x=1:100,replace=FALSE),recursive=TRUE)
aubk <- data.table(author_id = author_id,book_id = book_id)
aubk[order(book_id,author_id),]

这里有人看到作者27和36共同编写了第2册,所以他们应该在同一个小组中。作者63和100同样为3;和D,F和L为4.依此类推。

除了for循环之外,我想不出一个好的方法,这个(你可以猜到)很慢。我试了一下data.table以避免不必要的复制。有没有更好的方法呢?

aubk$group <- integer(dim(aubk)[1])
library(data.table)
aubk <- data.table(aubk)
#system.time({
for (x in 1:dim(aubk)[1]) {
    if(identical(x,1)) {
        value <- 1L
    } else {
        sb <- aubk[1:(x-1),]
        index <- match(aubk[x,author_id],sb[,author_id])
        if (identical(index,NA_integer_)) {
            index <- match(aubk[x,book_id],sb[,book_id])
            if (identical(index,NA_integer_)) {
                value <- x
            } else {
                value <- aubk[index,group]
            }
        } else {
            value <- aubk[index,group]
        }
    }
    aubk[x,group:=value]
}
#})

编辑:正如@Josh O'Brien和@thelatemail所提到的,我的问题也可以说是从两列列表中查找图表的连通组件,其中每个边缘都是行,两列是连接的节点。

3 个答案:

答案 0 :(得分:3)

将500K节点转换为邻接矩阵对我的计算机内存来说太多了,所以我无法使用igraph。对于R版本2.15.1,RBGL包不会更新,因此也没有更新。

在编写了许多似乎不起作用的愚蠢代码之后,我认为以下内容可以帮助我找到正确的答案。

aubk[,grp := author_id]
num.grp.old <- aubk[,length(unique(grp))]
iterations <- 0
repeat {
    aubk[,grp := min(grp),by=author_id]
    aubk[,grp := min(grp), by=book_id]
    num.grp.new <- aubk[,length(unique(grp))] 
    if(num.grp.new == num.grp.old) {break}
    num.grp.old <- num.grp.new
    iterations <- iterations + 1
}

答案 1 :(得分:1)

以下是我对Josh O'Brien在评论(identify groups of linked episodes which chain together)中所链接的旧问题的回答。这个答案使用igraph库。

# Dummy data that might be easier to interpret to show it worked
# Authors 1,2 and 3,4 should group. author 5 is a group to themselves
aubk <- data.frame(author_id=c(1,2,3,4,5),book_id=c(1,1,2,2,5))

# identify authors with a bit of leading text to prevent clashes 
# with the book ids
aubk$author_id2 <- paste0("au",aubk$author_id)

library(igraph)
#create a graph - this needs to be matrix input
au_graph <- graph.edgelist(as.matrix(aubk[c("author_id2","book_id")]))
# get the ids of the authors
result <- data.frame(author_id=names(au_graph[1]),stringsAsFactors=FALSE)
# get the corresponding group membership of the authors
result$group <- clusters(au_graph)$membership

# subset to only the authors data
result <- result[substr(result$author_id,1,2)=="au",]
# make the author_id variable numeric again
result$author_id <- as.numeric(substr(result$author_id,3,nchar(result$author_id)))

> result
  author_id group
1         1     1
3         2     1
4         3     2
6         4     2
7         5     3

答案 2 :(得分:0)

一些建议

aubk[,list(author_list = list(sort(author_id))), by = book_id]

将提供作者组列表

以下内容将为每组作者创建唯一标识符,然后返回带有

的列表
  • 书数
  • 图书ID列表
  • book_ids的唯一标识符
  • 作者人数
每个独特的作者群

aubk[, list(author_list = list(sort(author_id)), 
            group_id = paste0(sort(author_id), collapse=','), 
            n_authors = .N),by =  book_id][,
        list(n_books = .N, 
             n_authors = unique(n_authors), 
             book_list = list(book_id), 
             book_ids = paste0(book_id, collapse = ', ')) ,by = group_id]

如果作者订单很重要,只需删除sort并定义author_listgroup_id

修改

注意到上述内容,虽然有用但没有做适当的分组

也许以下

# the unique groups of authors by book
unique_authors <- aubk[, list(sort(author_id)), by = book_id]
# some helper functions
# a filter function that allows arguments to be passed
.Filter <- function (f, x,...) 
{
  ind <- as.logical(sapply(x, f,...))
  x[!is.na(ind) & ind]
}

# any(x in y)?
`%%in%%` <- function(x,table){any(unlist(x) %in% table)}
# function to filter a list and return the unique elements from 
# flattened values
FilterList <- function(.list, table) {
  unique(unlist(.Filter(`%%in%%`, .list, table =table)))
}

# all the authors
all_authors <- unique(unlist(unique_authors))
# with names!
setattr(all_authors, 'names', all_authors)
# get for each author, the authors with whom they have
# collaborated in at least 1 book
lapply(all_authors, FilterList, .list = unique_authors)