循环调用read_excel读取指定范围时遇length(x)==1L报错求助
问题原因及解决方案
报错原因
你遇到的Error in as.cell_limits.character(range) : length(x) == 1L is not TRUE错误,核心原因是内层循环中read_excel的参数写法错误:
- 你误将
range参数写成了函数调用range("F22:F30"),这会触发R内置的range()函数(用于计算数值范围),而非给read_excel的range参数赋值。这种错误导致readxl包无法正确解析单元格范围,触发类型不匹配的报错。
修正后的代码
library(readxl) library(stringr) library(dplyr) path <- "my file path" files_list <- list.files(path, pattern="*.xlsx", full.names = TRUE) files_list_names <- str_extract(list.files(path, pattern="*.xlsx"),"[^.]+") ###extract filename without file extension count_files <- length(files_list_names) # 推荐用列表存储结果,避免assign创建全局变量 result_list <- list() for (i in 1:count_files){ current_file <- files_list_names[i] # 读取初始数据 current_file_data <- read_excel(files_list[i], range = "B22:B30") this_file_sheets <- excel_sheets(files_list[i]) count_sheets <- length(this_file_sheets) for (j in 1:count_sheets){ # 修正range参数写法:用range = "F22:F30"而非函数调用 current_sheet_data <- read_excel(files_list[i], sheet = this_file_sheets[j], range = "F22:F30") # 将合并结果重新赋值,否则数据会丢失 current_file_data <- bind_cols(current_file_data, current_sheet_data) } # 存入列表 result_list[[current_file]] <- current_file_data # 若坚持要创建全局变量,保留以下代码 # assign(current_file, current_file_data, envir = .GlobalEnv) }
额外注意事项
- 原代码中
bind_cols的结果未赋值回current_file_data,导致每次循环的合并数据都丢失,修正后必须重新赋值才能保留结果。 - 尽量避免使用
assign创建全局变量,用列表存储结果更符合R的编码规范,也方便后续批量处理。 - 确保已加载
dplyr、readxl、stringr这三个依赖包。
内容的提问来源于stack exchange,提问作者Florian
相关产品推荐
相关产品推荐

