如何批量合并变量名形如output1至output100的多个data frame?
Hey there! Merging 100 data frames by typing each name manually is such a tedious task—let’s cut that work down to a few lines of code with these practical R solutions:
mget() + do.call(rbind, ...)(最简洁高效) This is my go-to method for this kind of job. mget() grabs all the objects whose names match your pattern and stores them in a list, then do.call() applies rbind() to every element of that list in one go:
# 生成数据框名称的字符向量 df_names <- paste0("output", 1:100) # 获取所有数据框并合并 combined_df <- do.call(rbind, mget(df_names))
If you prefer a more explicit approach, a simple loop works too. Start with your first data frame, then iterate through the rest and bind them one by one:
# 用第一个数据框初始化合并结果 combined_df <- output1 # 从output2循环到output100 for (i in 2:100) { # 通过名称获取当前数据框 current_df <- get(paste0("output", i)) # 合并到总数据框中 combined_df <- rbind(combined_df, current_df) }
dplyr::bind_rows()(Tidyverse用户首选) If you’re using the tidyverse, bind_rows() is even cleaner. It handles cases where data frames have slightly different columns (filling missing ones with NA) more gracefully than base R’s rbind:
library(dplyr) # 生成名称并一步完成合并 df_names <- paste0("output", 1:100) combined_df <- bind_rows(mget(df_names))
小提示:
- 确保所有数据框的列名和数据类型匹配。如果不匹配,
rbind()会报错(或强制转换类型),而bind_rows()会自动为缺失列填充NA。 - 如果你的环境中还有其他名为
outputXX的非数据框对象,可以调整paste0的生成规则,或者对mget()返回的列表进行过滤,只保留数据框类型。
All these methods will save you the headache of typing 100 variable names. Pick the one that fits your workflow best!
内容的提问来源于stack exchange,提问作者Sonal Bajoriya

