为列表中各数据框的所有行添加数据框名称列
Got it, let's tackle this problem step by step—you want to add a column to each data frame that holds the data frame's name, then combine them all to track row origins. Here are a few straightforward methods, including using dplyr like you started with:
Single Data Frame (dplyr Approach)
For your example test_df, you can use mutate() along with deparse(substitute()) to grab the data frame's name as a string:
library(dplyr) # Your example data frame test_df <- data.frame(x = 1:5, y = c("a","b","c","d","e")) # Add the ref column with the data frame's name test_df <- test_df %>% mutate(ref = deparse(substitute(test_df)))
This will create a ref column where every row has the value "test_df"—exactly what you wanted!
Multiple Data Frames (Batch Processing with Tidyverse)
If you have multiple data frames to process and merge, using a named list + purrr::imap() is the cleanest way (it plays nicely with dplyr):
library(purrr) library(dplyr) # Example additional data frames test_df1 <- data.frame(x = 1:3, y = c("a","b","c")) test_df2 <- data.frame(x = 4:6, y = c("d","e","f")) # Store data frames in a NAMED list (names = data frame names) df_list <- list(test_df = test_df, test_df1 = test_df1, test_df2 = test_df2) # Add ref column to each data frame (uses the list's names as ref values) df_list_with_ref <- df_list %>% imap(~ mutate(.x, ref = .y)) # Merge all into one data frame combined_df <- bind_rows(df_list_with_ref)
imap()iterates over the list, where.xis each data frame and.yis its corresponding name in the list.bind_rows()replacesrbind()for cleaner tidyverse-style merging.
Base R Alternative
If you prefer not to use tidyverse packages, here's how to do it with base R:
Single Data Frame
test_df$ref <- deparse(substitute(test_df))
Multiple Data Frames
# Create named list of data frames df_list <- list(test_df = test_df, test_df1 = test_df1, test_df2 = test_df2) # Add ref column to each df_list_with_ref <- lapply(names(df_list), function(name) { df <- df_list[[name]] df$ref <- name return(df) }) # Merge with base R's rbind combined_df <- do.call(rbind, df_list_with_ref)
Key Notes
deparse(substitute(df))works for single data frames because it captures the variable name as a string. For batch processing, using the list's names is more reliable (especially if you're working inside functions).- After merging, you can filter rows by the
refcolumn to easily trace back which data frame they came from.
内容的提问来源于stack exchange,提问作者Haakonkas

