Skip to content

Instantly share code, notes, and snippets.

@pj398
Created April 30, 2020 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pj398/7b149797e2cdc665ad52a7232fd3dfb8 to your computer and use it in GitHub Desktop.
Save pj398/7b149797e2cdc665ad52a7232fd3dfb8 to your computer and use it in GitHub Desktop.
R implementation of narrative centrality measure for character interaction networks
narrative_centrality <- function(event_list,
chars = NULL,
mode = "both",
wp = 0.01,
normalised = TRUE,
start_at = 1) {
C_in <- matrix(1, nrow(event_list), length(chars))
C_out <- matrix(1, nrow(event_list), length(chars))
C_in_norm <- matrix(1, nrow(event_list), length(chars))
C_out_norm <- matrix(1, nrow(event_list), length(chars))
if(is.null(chars)) {
chars <- colnames(event_list)[start_at + 1:ncol(event_list)]
}
colnames(C_in) <- chars
colnames(C_in_norm) <- chars
colnames(C_out) <- chars
colnames(C_out_norm) <- chars
# Compute the scores
C_in_t <- matrix(1, length(chars), 1)
C_out_t <- matrix(1, length(chars), 1)
for (t in 1:nrow(event_list)) {
speaker <- event_list[t, start_at]
receivers <- which(event_list[t, (start_at + 1):dim(event_list)[2]] == 1)
C_in_t[receivers] <- C_in_t[receivers] + (wp * C_in_t[speaker])
C_out_t[speaker] <- C_out_t[speaker] +
((wp / length(receivers)) * sum(C_out_t[receivers]))
for (c in 1:length(chars)) {
C_in[t, c] <- C_in_t[c]
C_out[t, c] <- C_out_t[c]
C_in_norm[t, c] <- C_in_t[c] / sum(C_in_t)
C_out_norm[t, c] <- C_out_t[c] / sum(C_out_t)
}
}
# Return the requested values according to `normalised` and `mode`
if(normalised == TRUE) {
if(mode == "both") {
return(list("out_scores" = C_out_norm, "in_scores" = C_in_norm))
}
if(mode == "in") {
return(C_in_norm)
}
if(mode == "out") {
return(C_out_norm)
}
} else {
if(mode == "both") {
return(list(C_out, C_in))
}
if(mode == "in") {
return(C_in)
}
if(mode == "out") {
return(C_out)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment