-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05_minibatching_sampling.R
48 lines (35 loc) · 1.59 KB
/
05_minibatching_sampling.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
library(amen)
library(rstan)
data(IR90s)
# A function to convert a matrix of pairs to an edgelist
# Assumes that rows == columns, but will check
matrix_to_edgelist <- function(sociomatrix_to_convert){
if(nrow(sociomatrix_to_convert) != ncol(sociomatrix_to_convert)){
stop("nrows != ncols")
}
all_nodes <- expand.grid(
list(rownames(sociomatrix_to_convert), colnames(sociomatrix_to_convert)))
all_nodes[, 1] <- as.numeric(all_nodes[, 1])
all_nodes[, 2] <- as.numeric(all_nodes[, 2])
all_nodes <- all_nodes[all_nodes[, 1] != all_nodes[, 2], ]
lookup_table <- data.frame(
node_names = rownames(sociomatrix_to_convert),
idx = as.numeric(factor(rownames(sociomatrix_to_convert))))
obs_values <- which(sociomatrix_to_convert != 0, arr.ind = TRUE)
obs_values <- cbind(obs_values, sociomatrix_to_convert[obs_values])
edgelist <- merge(
all_nodes, obs_values, by.x = c("Var1", "Var2"),
by.y = c("row", "col"), all.x = TRUE)
edgelist$V3 <- ifelse(is.na(edgelist$V3), 0, edgelist$V3)
edgelist <- cbind(
edgelist,
rep(seq.int(from = 1, to = sum(edgelist[, 1] < edgelist[, 2])), 2))
edgelist <- cbind(edgelist, ifelse(edgelist[, 1] < edgelist[, 2], 1, 2))
colnames(edgelist) <- c("sender", "receiver", "y", "dyad_id", "sr_indicator")
# for dyad list include a (1, 2) indicator for send/receive
# if s < r -> 1, else 2
return(list(edgelist = edgelist, lookup_table = lookup_table,
n_nodes = max(edgelist[, 1]), n_dyads = max(edgelist[, 4]),
N = nrow(edgelist)))
}
data_for_stan <- matrix_to_edgelist(IR90s$dyadvars[, , 2]) # trade data