【发布时间】:2018-03-13 05:41:12
【问题描述】:
假设我们有以下玩具数据:
library(tidyverse)
data <- tibble(
subject = c(1, 1, 1, 2, 2, 2, 2, 3, 3, 3),
id1 = c("a", "a", "b", "a", "a", "a", "b", "a", "a", "b"),
id2 = c("b", "c", "c", "b", "c", "d", "c", "b", "c", "c")
)
代表每个主题的网络关系。例如,数据中有三个唯一的主题,第一个主题的网络可以表示为关系序列:
a -- b, a --c, b -- c
任务是计算每个网络的中心性。使用 for 循环很简单:
library(igraph)
# Get unique subjects
subjects_uniq <- unique(data$subject)
# Compute centrality of nodes for each graph
for (i in 1:length(subjects_uniq)) {
current_data <- data %>% filter(subject == i) %>% select(-subject)
current_graph <- current_data %>% graph_from_data_frame(directed = FALSE)
centrality <- eigen_centrality(current_graph)$vector
}
问题:我的数据集很大,所以我想知道如何避免显式的for 循环。我应该使用apply() 及其现代表亲(可能是purrr 包中的map())?非常欢迎任何建议。
【问题讨论】: