michellis
michellis

Reputation: 15

How to calculate ties for network analysis from raw data

I have some data on published papers that looks like this:

paper <- c("paper1", "paper1", "paper2", "paper3", "paper3", "paper4", "paper4", "paper5")
author <- c("author1", "author2", "author1", "author2", "author1", "author2", "author3", "author2")
df1 <- data.frame(paper, author) 

How can I get to this format to run network analysis?

from <- c("a1", "a2", "a2")
to <- c("a2", "a3", "a3")
weight <- c(2,0,1)
df2 <- data.frame(from, to, weight)

I have tried meddling with pivot_wider() and widyr::pairwise_count but haven't produced the desired output yet.

Upvotes: 1

Views: 96

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388907

Here's a base R option -

Create a pairwise combination with combn and use tapply to count how many papers have the combination in them

result <- do.call(rbind, combn(unique(df1$author), 2, function(x) {
    data.frame(from = x[1], to = x[2], 
          weight = sum(tapply(df1$author, df1$paper, function(y) all(x %in% y))))
}, simplify = FALSE))

result

#     from      to weight
#1 author1 author2      2
#2 author1 author3      0
#3 author2 author3      1

Upvotes: 1

Related Questions