【问题标题】:Quick function for Carrying Subsets in RR中携带子集的快速函数
【发布时间】:2016-10-15 03:31:06
【问题描述】:

我想计算我的数据集中每个作者有多少次合作,我的数据就像

第一列是作者,第二列是文章 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)

但是这种循环很慢,因为我有超过 1000000 个作者,有什么快速的方法吗?

【问题讨论】:

  • 能否请您给出一个小样本数据集和预期输出? “..计算每个作者有多少次合作......”这是否意味着“对于每个作者,有多少其他作者与这个作者合作过?”
  • 没错……

标签: r loops subset


【解决方案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]

【讨论】:

  • uniqueN(author) 计算唯一案例,而 .N 计算所有案例。
【解决方案2】:

我通读了 cmets,我想我得到了你想要达到的目标 我创建了一个模拟您的情况的虚拟示例。

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”, “维杰”和“塔伦”)。

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

希望这会有所帮助。

【讨论】:

  • count(...) 很方便;同group_by(...) %&gt;% summarise(n = n()
猜你喜欢
  • 2013-07-03
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 2019-04-15
相关资源
最近更新 更多