在迭代列[R]中的唯一值时如何避免for循环
假设我们有以下玩具数据:在迭代列[R]中的唯一值时如何避免for循环,r,for-loop,tidyverse,R,For Loop,Tidyverse,假设我们有以下玩具数据: 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") ) 任务是计算每个网络的中心度。使用for循环这很简单: lib
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")
)
任务是计算每个网络的中心度。使用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
}
库(igraph)
#获得独特的主题
受试者\u uniq%选择(-subject)
当前\u图形%graph\u来自\u数据\u帧(directed=FALSE)
中心性这里有一个使用map
library(tidyverse)
library(igraph)
map(subjects_uniq, ~data %>%
filter(subject == .x) %>%
select(-subject) %>%
graph_from_data_frame(directed = FALSE) %>%
{eigen_centrality(.)$vector})
#[[1]]
#a b c
#1 1 1
#[[2]]
# a b c d
#1.0000000 0.8546377 0.8546377 0.4608111
#[[3]]
#a b c
#1 1 1
library(tidyverse)
library(igraph)
map(subjects_uniq, ~data %>%
filter(subject == .x) %>%
select(-subject) %>%
graph_from_data_frame(directed = FALSE) %>%
{eigen_centrality(.)$vector})
#[[1]]
#a b c
#1 1 1
#[[2]]
# a b c d
#1.0000000 0.8546377 0.8546377 0.4608111
#[[3]]
#a b c
#1 1 1