在R中读取多个Excel文件后,如何根据文件名创建Mon_Year列?
解决Excel文件批量读取后添加Mon_Year列的问题
你需要给每个读取后的Excel数据框添加Mon_Year列,值对应文件名中的月份缩写+年份,以下是修改后的实现方案:
修正后的完整代码
首先加载所需包,然后修改批量处理逻辑,从文件名中提取并转换所需信息:
library(readxl) library(stringr) # 获取目标xlsx文件路径(修正匹配规则,仅匹配xlsx文件) files <- list.files(pattern = "\\.xlsx$", path = "wd", recursive = TRUE, full.names = TRUE) # 定义处理单个文件的函数:读取并添加Mon_Year列 process_file <- function(file_path) { # 读取Excel文件 df <- read_excel(file_path) # 从文件名提取月份全称和年份 file_name <- basename(file_path) mon_year_match <- str_match(file_name, "(\\w+) (\\d{4})\\.xlsx$") mon_full <- mon_year_match[, 2] year <- mon_year_match[, 3] # 将月份全称转换为缩写(兼容小写月份名) mon_abbr <- month.abb[match(str_to_title(mon_full), month.name)] # 组合成Mon_Year列的值 mon_year <- paste(mon_abbr, year) # 添加新列 df$Mon_Year <- mon_year return(df) } # 批量处理所有文件,得到带新列的数据框列表 lst_of_frames <- lapply(files, process_file)
不用stringr的base R版本
如果不想依赖stringr包,可以用base R实现:
library(readxl) files <- list.files(pattern = "\\.xlsx$", path = "wd", recursive = TRUE, full.names = TRUE) process_file_base <- function(file_path) { df <- read_excel(file_path) file_name <- basename(file_path) # 拆分文件名提取月份和年份 name_parts <- strsplit(file_name, " ")[[1]] mon_full <- name_parts[length(name_parts)-1] year <- gsub("\\.xlsx$", "", name_parts[length(name_parts)]) # 转换月份为缩写 mon_abbr <- month.abb[match(toupper(mon_full), toupper(month.name))] mon_year <- paste(mon_abbr, year) df$Mon_Year <- mon_year return(df) } lst_of_frames <- lapply(files, process_file_base)
关键说明
- 文件匹配修正:原代码的
pattern = "*.xls"会匹配xls文件,改为\\.xlsx$确保只匹配你的xlsx格式文件。 - 月份兼容处理:针对文件名中存在小写的
march,通过str_to_title或toupper统一格式后,再与month.name匹配转换为缩写。 - 列添加逻辑:每个文件读取后,直接为该数据框添加
Mon_Year列,值为对应文件名转换后的月份缩写+年份,保证每行都有对应值。
内容的提问来源于stack exchange,提问作者Binod
相关产品推荐
相关产品推荐

