如何在tidygraph中结合group_by()使用as_tbl_graph()?
Got it, let's work through these tidygraph and dplyr grouping issues one by one—they're common pitfalls when combining tidyverse workflows with graph data!
1. Fixing as_tbl_graph() behavior with grouped data frames
When you run tmp %>% group_by(id_head, id_sec) %>% as_tbl_graph(), you're not creating separate graphs per group—instead, as_tbl_graph() treats the entire grouped tibble as a single edge list. The grouping columns (id_head, id_sec) get added as edge attributes, and the guess_df_type() heuristic is confused by the grouped structure, leading it to misidentify which columns represent nodes/edges.
To generate one graph per group, use group_modify() to apply as_tbl_graph() individually to each subgroup. This also lets you explicitly set the from and to parameters without renaming columns, which is cleaner:
library(tidygraph) library(tidyverse) tmp <- tibble( id_head = as.integer(c(4,4,4,4,4,4,5,5,5,5)), id_sec = as.integer(c(1,1,1,2,2,2,1,1,2,2)), token = as.integer(c(1,2,3,1,2,3,1,2,1,2)), head = as.integer(c(2,2,2,1,1,2,2,2,2,2)), root = as.integer(c(2,2,2,1,1,1,2,2,2,2)) ) # Create a tibble where each row holds a graph for one (id_head, id_sec) group grouped_graphs <- tmp %>% group_by(id_head, id_sec) %>% group_modify(~ as_tbl_graph(.x, directed = FALSE, from = token, to = head)) # Example: Access the graph for id_head=4, id_sec=1 grouped_graphs %>% filter(id_head == 4, id_sec == 1) %>% pull(.result)
The group_modify() function iterates over each group, passes the subgroup data to as_tbl_graph(), and stores the resulting graphs in a .result column.
2. Fixing the group_by() error on a tbl_graph object
When you call group_by() directly on a tbl_graph, it defaults to grouping the node table—but your id_head and id_sec columns are stored in the edge table (since they came from your original edge list tibble). That's why you get the "Column id_head is unknown" error—the node table doesn't have those columns.
If you want to group edge attributes (for operations like summarizing edges per group), activate the edge table first with activate(edges):
# Create a single graph with edge attributes intact single_graph <- tmp %>% as_tbl_graph(directed = FALSE, from = token, to = head) # Group the edges by id_head and id_sec single_graph %>% activate(edges) %>% group_by(id_head, id_sec)
If your goal is to work with separate subgraphs per group, the group_modify() approach from section 1 is better—grouping edges in a single graph is for attribute-based operations, not splitting the graph into independent subgraphs.
内容的提问来源于stack exchange,提问作者Paavo Pohndorff

