我有以下图表:
library(igraph)
n_rows <- 10
n_cols <- 5
g <- make_lattice(dimvector = c(n_cols, n_rows))
layout <- layout_on_grid(g, width = n_cols)
n_nodes <- vcount(g)
node_colors <- rep("white", n_nodes)
for (row in 0:(n_rows-1)) {
start_index <- row * n_cols + 1
node_colors[start_index:(start_index+2)] <- "orange"
node_colors[(start_index+3):(start_index+4)] <- "purple"
}
node_labels <- 1:n_nodes
plot(g,
layout = layout,
vertex.color = node_colors,
vertex.label = node_labels,
vertex.label.color = "black",
vertex.size = 15,
edge.color = "gray",
main = "Rectangular Undirected Network")
在之前的问题(随机将图拆分为小图)中,我学习了如何将该图拆分为 5 个连通的小子图:
library(data.table)
f <- function(g, n) {
m <- length(g)
dt <- setDT(as_data_frame(g))
dt <- rbindlist(list(dt, dt[,.(from = to, to = from)]))
dt[,group := 0L]
used <- logical(m)
s <- sample(m, n)
used[s] <- TRUE
m <- m - n
dt[from %in% s, group := .GRP, from]
while (m) {
dt2 <- unique(
dt[group != 0L & !used[to], .(grow = to, onto = group)][sample(.N)],
by = "grow"
)
dt[dt2, on = .(from = grow), group := onto]
used[dt2[[1]]] <- TRUE
m <- m - nrow(dt2)
}
unique(dt[,to := NULL])[,.(vertices = .(from), .N), group]
}
问题:假设我运行此函数 25 次并存储
generate_multiple_subgraphs <- function(n_iterations = 25, n_rows = 10, n_cols = 5, n_subgraphs = 5) {
g <- make_lattice(dimvector = c(n_cols, n_rows))
subgraph_list <- lapply(1:n_iterations, function(i) {
f(g, n_subgraphs)
})
return(subgraph_list)
}
subgraph_sets <- generate_multiple_subgraphs()
在每个子图中,我想计算每个分区中紫色节点(相对于原始颜色,即开始时为紫橙色的图)的百分比。
我能够得到原始图表的摘要:
original_node_data <- data.frame(
Node = 1:n_nodes,
Color = node_colors
)
但我不确定如何将此数据框合并到子图列表中以获得如下结果:
subgraph partition total_nodes purple_nodes percent_purple
<int> <int> <int> <int> <num>
1: 1 1 14 8 57.14286
2: 1 2 12 2 16.66667
3: 1 3 4 0 0.00000
4: 1 4 9 6 66.66667
5: 1 5 11 4 36.36364
---
121: 25 1 13 3 23.00000
122: 25 2 6 6 100.00000
123: 25 3 9 0 0.00000
124: 25 4 8 5 62.50000
125: 25 5 14 6 42.00000
有人可以告诉我怎么做吗?
你可能想要类似的东西
给予
编辑:在里面
transform()
您可以创建更多变量;就像这个例子显示的那样purple
。