在R语言中将层级DataFrame转换为嵌套列表的实现问题
Hey there! Let's work through converting your df into that nested goal_list structure you need—since you're new to list manipulation, I'll break this down step by step with clear examples.
First, I noticed your sample df only includes a Manager column, but we'll need an Employee column too (otherwise we can't map who reports to whom). Let's start with a realistic sample df matching your manager names:
library(tidyverse) library(data.tree) # Sample data frame with Manager -> Employee relationships df <- tibble( Manager = c(rep("Robert Baratheon", 7), "Robert Baratheon", "Eddard Stark", rep("Barristan Selmy", 4)), Employee = c("Ned Stark", "Jaime Lannister", "Cersei Lannister", "Joffrey Baratheon", "Myrcella Baratheon", "Tommen Baratheon", "Varys", "Eddard Stark", "Jory Cassel", "Aerys II Targaryen", "Rhaegar Targaryen", "Viserys Targaryen", "Daenerys Targaryen") )
Method 1: Use data.tree (simplest for hierarchical structures)
Since you're already loading data.tree, this package is perfect for turning flat employee-manager data into nested lists. Here's how:
- First, convert your df into a
data.treeNode structure by creating a path string:
# Create a path string (Root -> Manager -> Employee) for hierarchy tree_df <- df %>% mutate(pathString = paste("Root", Manager, Employee, sep = "/")) # Convert to a data.tree Node hierarchy_tree <- as.Node(tree_df)
- Now convert the tree to your target nested list. If you want managers as the top-level items (no "Root" node), do this:
# Extract managers as top-level list items, with their employees as sub-lists goal_list <- setNames( lapply(hierarchy_tree$children, function(manager_node) { # For each manager, get their employees as a nested list (empty lists here, adjust if you need sub-subordinates) setNames(lapply(manager_node$children, function(emp_node) list()), names(manager_node$children)) }), names(hierarchy_tree$children) )
Method 2: Manual list building (great for learning)
If you want to understand the list manipulation without data.tree, here's a tidyverse-only approach:
goal_list <- df %>% # Group by each manager group_by(Manager) %>% # For each manager, collect their employees into a list summarise(employees = list(Employee)) %>% # Convert the two-column tibble into a named vector (Manager names as list keys) deframe() %>% # Turn each employee list into a nested list structure lapply(function(emp_names) { setNames(lapply(emp_names, function(name) list()), emp_names) })
Quick Notes for Customization:
- If your
goal_listneeds deeper nesting (e.g., employees who are managers themselves), just add their direct reports to the df with their own Manager entries. Thedata.treemethod will automatically handle multi-level hierarchies. - If you need to include additional data (like employee roles) in the nested lists, just add those columns to the df and adjust the
lapplysteps to include them.
内容的提问来源于stack exchange,提问作者Sobo
相关产品推荐
相关产品推荐

