R中携带子集的快速功能

时间:2016-10-15 03:31:07

标签: r loops subset

我想计算数据集中每位作者的合作次数,我的数据就像this

第一列是作者,第二列是文章ID。所以每篇文章都是由一位独家作者或几位作者撰写的。

我使用的代码基本上是一个循环,

degree1 <- rep(NA, length(Name))

for(i in 1:length(Name)){
    temp <- subset(mydata, mydata$data == Name[i])  
    temp <- subset(mydata, mydata[, 2] %in% temp$artid)
    CC <- unique(temp$data)
    degree1[i] <- length(CC) - 1
    print(i)
}

其中Name是使用

的作者向量
Name <- unique(mydata$data)

但是这种循环非常慢,因为我有超过100万作者,有没有快速的方法呢?

2 个答案:

答案 0 :(得分:1)

library(data.table)

# make dataset
n = 20
set.seed(123)
x = data.table(
  author = LETTERS[1:n],
  artid = sample.int(n, replace = T)
)
x = x[order(artid)]

# collaborations
x[, n := uniqueN(author), by = artid]

答案 1 :(得分:0)

我读完了评论,我想我得到了你想要达到的目标 我创建了一个模仿你情况的虚拟例子。

library(dplyr)
art_id <- c(11, 11, 11, 10, 10)
author <- c("Ajay","Vijay","Shyam",
            "Ajay","Tarun")
uniq_art <- unique(art_id) # get unique article id

所以在这种情况下,Ajay与三位作者合作('Shyam', 'Vijay'和'Tarun')。

Shyam和Vijay各自与两位作者合作 Tarun只与一位作者合作。 我对你的问题的解决方案不是很优雅。 希望有人能提供更优雅的解决方案。

# Make the data frame
publish <- data.frame(art_id, author)

# subset for a particular aritcle ID 
# group by author and get the number of authors each author 
# has worked with

b <- publish %>% filter(art_id == uniq_art[1]) 
c <- b %>% group_by(author) %>% summarise(ans = dim(b)[1]-1)

# Repeat the process and join results to above data frame
# for the remaining article IDs

for(i in 2:length(uniq_art)) {
  b <- publish %>% filter(art_id == uniq_art[i]) 
  d <- b %>% group_by(author) %>% summarise(ans = dim(b)[1]-1)
  c <- full_join(c, d, by = "author")
}    

# get the number of columns
nc <- ncol(c)

# sample output after running loop in my dummy case

# A tibble: 4 x 3
  author ans.x ans.y
  <fctr> <dbl> <dbl>
 1   Ajay     2     1
 2  Shyam     2    NA
 3  Vijay     2    NA
 4  Tarun    NA     1

# Add all numeric values in each row to get total collaborated authors    
total_collab <- rowSums(c[,2:nc], na.rm = T)
final_ans <- c %>% mutate(total = total_collab)
final_ans

# A tibble: 4 x 4
  author ans.x ans.y total
  <fctr> <dbl> <dbl> <dbl>
1   Ajay     2     1     3
2  Shyam     2    NA     2
3  Vijay     2    NA     2
4  Tarun    NA     1     1

希望这有帮助。