You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中基于文件名筛选文件并合并指定列到tibble?

高效筛选并合并带特征文件名的CSV文件到Tibble(Tidyverse方案)

完整解决方案代码

library(tidyverse)

# 1. 读取文件列表并解析文件名特征
file_info <- tibble(file_path = list.files(path = "data-cleaned", full.names = TRUE)) %>%
  # 提取纯文件名(移除路径和.csv后缀)
  mutate(file_name = str_remove(file_path, ".*/") %>% str_remove("\\.csv$")) %>%
  # 按下划线拆分文件名到特征列,缺失字段补空
  separate(file_name, into = c("group_A", "treatment", "reec_status", "time_point"), sep = "_", fill = "right") %>%
  # 从T=X格式中提取时间点数字
  mutate(time_point = str_extract(time_point, "\\d+"))

# 2. 定义筛选条件(可灵活组合)
# 示例1:筛选所有SORE6处理的文件
sore6_files <- file_info %>% filter(treatment == "SORE6") %>% pull(file_path)
# 示例2:筛选A5组+minCMV处理的文件
a5_mincmv_files <- file_info %>% filter(group_A == "A5", treatment == "minCMV") %>% pull(file_path)

# 3. 批量读取并合并指定列的函数
read_and_combine <- function(file_paths, target_cols) {
  map_dfr(file_paths, ~read_csv(.x, col_select = all_of(target_cols)))
}

# 生成目标tibble
SORE6 <- read_and_combine(sore6_files, "Ch1_IntNorm")
minCMV <- read_and_combine(filter(file_info, treatment == "minCMV") %>% pull(file_path), "Ch1_IntNorm")

逐步骤解释

步骤1:解析文件名特征

这一步是核心,把文件名里的结构化信息拆成单独列,方便后续灵活筛选:

  • tibble(file_path = list_files(...)):把文件路径转换成tibble,适配tidyverse工具链
  • str_remove(file_path, ".*/"):移除文件路径,只保留文件名;str_remove("\\.csv$")移除.csv后缀
  • separate(..., sep = "_"):按下划线把文件名拆成多个特征列,fill="right"确保即使文件名段数不同也不会报错
  • str_extract(time_point, "\\d+"):从T=1这类字符串中提取数字,方便后续按时间点筛选

步骤2:灵活筛选文件

用filter()可以组合任意条件,比如:

  • 单条件:filter(treatment == "minCMV")
  • 多条件组合:filter(group_A == "A1", reec_status == "REEC", time_point == "5")
    筛选完成后用pull(file_path)提取需要处理的文件路径列表

步骤3:批量读取合并

  • map_dfr():来自purrr包,遍历文件路径列表,对每个文件执行read_csv(),最后自动按行合并成一个tibble
  • col_select = all_of(target_cols):确保传入的列名字符串能被正确识别,支持单列或多列(比如c("Ch1_IntNorm", "Ch1_IntDen"))
  • 这个函数可重复调用,只要传入不同的文件列表和目标列,复用性极强

更多灵活用法示例

提取多个列

# 同时提取Ch1_IntNorm和Ch1_IntDen两列
SORE6_multi_cols <- read_and_combine(sore6_files, c("Ch1_IntNorm", "Ch1_IntDen"))

按时间点筛选合并

# 筛选所有T=1的文件并合并Ch1_IntNorm列
t1_data <- read_and_combine(
  file_info %>% filter(time_point == "1") %>% pull(file_path),
  "Ch1_IntNorm"
)

按A组编号筛选

# 合并所有A1组的文件的Ch1_RawIntDen列
A1_data <- read_and_combine(
  file_info %>% filter(group_A == "A1") %>% pull(file_path),
  "Ch1_RawIntDen"
)

内容的提问来源于stack exchange,提问作者gvit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 19:13:30