我想知道是否有人可以帮助我这个for循环。或者建议另一种方法获得我想要的东西(我知道代码有点像噩梦,但是我被如何使它更优雅难住了)。
问题:我在一个列表中有一些网络对象;我想比较这些网络的一些社区检测算法。我想一次性获得这些信息(不像这里的玩具示例,我的真实列表中有许多网络)。下面的示例让我接近我想要的信息,但它没有在最终输出中列出网络。我需要做些什么才能在最终数据帧中也包含网络的名称?
library(graph)
library(igraphdata)
library(igraph)
# create a couple of networks
data(karate)
g2 <- erdos.renyi.game(50, .2)
# stick the networks in a list
list_of_networks <- list(karate, g2)
# get all the community detection algorithms
clusters <- grep("^cluster_", ls("package:igraph"), value=TRUE)[-1]
# get rid of the algorithms I don't want
clusters <- clusters[!grepl("spinglass|fluid|leiden|walktrap|infomap|prop|optimal", clusters)]
# for loop stuff
# there are two networks in the network list
x <- 1:2
# a container for my for loop results
container <- vector("list", length = 2)
# nested for loop
for (cluster in clusters) {
for (i in x) {
result <- t(c(
modularity(do.call(cluster, list(list_of_networks[[i]]))),
length(do.call(cluster, list(list_of_networks[[i]]))),
cluster
))
container[[i]] <- rbind(result, container[[i]])
}
}
container %>%
map(~ as_tibble(.)) %>%
bind_rows() %>%
rename(modularity = 1,
num_communities = 2,
algorithm = 3)
您可以使用map_df
的.id
参数:
library(tidyverse)
container %>%
map_df(~ as_tibble(.) %>%
rename(modularity = 1,
num_communities = 2,
algorithm = 3),
.id = "name")
这返回
# A tibble: 6 × 4
name modularity num_communities algorithm
<chr> <chr> <chr> <chr>
1 1 0.443854125672307 4 cluster_louvain
2 1 0.4366391184573 5 cluster_leading_eigen
3 1 0.434521466989 3 cluster_fast_greedy
4 2 0.224687153369057 5 cluster_louvain
5 2 0.197245699823462 4 cluster_leading_eigen
6 2 0.193293130653502 4 cluster_fast_greedy
所以你的网络被命名为1
和2
。
为了获得更好的信息,我们在你的代码中添加一行
container <- vector("list", length = 2)
# Add names here
names(container) <- unlist(lapply(list_of_networks, (x) x$name))
# or
# names(container) <- sapply(list_of_networks, (x) x$name)
现在
container %>%
map_df(~ as_tibble(.) %>%
rename(modularity = 1,
num_communities = 2,
algorithm = 3),
.id = "name")
返回# A tibble: 6 × 4
name modularity num_communities algorithm
<chr> <chr> <chr> <chr>
1 Zachary's karate club network 0.444903581267218 4 cluster_louvain
2 Zachary's karate club network 0.4366391184573 5 cluster_leading_eigen
3 Zachary's karate club network 0.434521466989 3 cluster_fast_greedy
4 Erdos-Renyi (gnp) graph 0.210112108800672 4 cluster_louvain
5 Erdos-Renyi (gnp) graph 0.188379542113001 2 cluster_leading_eigen
6 Erdos-Renyi (gnp) graph 0.21151675068263 3 cluster_fast_greedy