R 在嵌套循环中使用lappy
我试图在随机网络对象列表上使用lappy()函数来为它们生成相应社区的列表(igraph包)。我已经在循环之外完成了这项工作,并且知道它工作正常 但是,我现在正在嵌套循环中生成网络,需要在我的内部循环之后使用lappy来生成此社区列表。我在外循环中记录这两个列表的平均描述值,以生成它们的数据帧R 在嵌套循环中使用lappy,r,function,loops,nested-loops,lapply,R,Function,Loops,Nested Loops,Lapply,我试图在随机网络对象列表上使用lappy()函数来为它们生成相应社区的列表(igraph包)。我已经在循环之外完成了这项工作,并且知道它工作正常 但是,我现在正在嵌套循环中生成网络,需要在我的内部循环之后使用lappy来生成此社区列表。我在外循环中记录这两个列表的平均描述值,以生成它们的数据帧 是否可以在嵌套循环中使用lappy()(或具有相同效果的内容),还是应该尝试编写具有相同目标的函数?我已经包括了一个代码示例来告诉你我的意思,当我使用行random\u cs运行代码时,我收到了错误消息,
是否可以在嵌套循环中使用lappy()(或具有相同效果的内容),还是应该尝试编写具有相同目标的函数?我已经包括了一个代码示例来告诉你我的意思,当我使用行
random\u cs运行代码时,我收到了错误消息,问题很可能来自cluster\u optimal
函数,该函数与lappy
一起使用。您应该查看本网站的帮助页面,了解如何提供一个可重复性最低的示例。@Suren我确实这样做了。如果您有igraph包,则代码是独立的。
random_nw_metrics <- data.frame( #to fill in
# Community
"count_communities" = NA,
"ave_membership" = NA,
"sd_membership" = NA,
"modularity" = NA,
# General Network
# "assortativity" = NA,
"ave_distance" = NA,
"degree_ave" = NA,
"degree_sd" = NA,
"density" = NA,
"diameter" = NA,
"reciprocity" = NA,
"transitivity" = NA
)
for (i in 1:180){ # it was "i in 1:nrow(df)", but that's not useful to you
set.seed(1)
random_nws <- list()
for (j in seq_len(1000L)) {
Start = sample(15, 200, replace=TRUE) # "15" and "20" change based on values from the df
End = sample(15, 200, replace=TRUE)
df = data.frame(Start, End)
ass.label <- data.frame("node" = 1:15, "type" = 0) # for assortativity labels
ass.label$type <- +(match(ass.label$node, sample(x = 15, size = 5) ) > 0)
ass.label[c("node", "type")][is.na(ass.label[c("node", "type")])] <- 0
random_nws[[j]]<- graph_from_data_frame(df, vertices = ass.label, directed=TRUE)
}
random_cs <- lapply(random_nws, cluster_optimal) #THIS IS THE THE LINE
nw <- random_nws[[i]]
random_nw_metrics <- rbind(random_nw_metrics, data.frame(
# Community
"count_communities" = mean(sapply(random_cs, function(x) mean(length(x)))),
"ave_membership" = mean(sapply(random_cs, function(x) mean(membership(x)))),
"sd_membership" = mean(sapply(random_cs, function(x) sd(membership(x)))),
"modularity" = mean(sapply(random_cs, function(x) mean(modularity(x)))),
# General Network
# "assortativity" = mean(sapply(random_nws, function(x) mean(assortativity(x, V(x)$Type, directed = T)))), # this isn't working ignore it for now
"ave_distance" = mean(sapply(random_nws, function(x) mean(mean_distance(x)))),
"degree_ave" = mean(sapply(random_nws, function(x) mean(degree(x)))),
"degree_sd" = mean(sapply(random_nws, function(x) sd(degree(x)))),
"density" = mean(sapply(random_nws, function(x) mean(edge_density(x)))),
"diameter" = mean(sapply(random_nws, function(x) mean(diameter(x)))),
"reciprocity" = mean(sapply(random_nws, function(x) mean(reciprocity(x)))),
"transitivity" = mean(sapply(random_nws, function(x) mean(transitivity(x))))
))
}
no loop for break/next, jumping to top level
2.
FUN(X[[i]], ...)
1.
lapply(random_nws, cluster_optimal)