使用future_apply并行处理文件时遇'dim(X) must have a positive length'错误求助
问题:使用future_apply并行处理文件时出现"dim(X) must have a positive length"错误
原本用for循环处理文件运行正常但速度较慢,为实现并行处理引入future.apply包,变量sub_files存储磁盘上压缩文件的路径列表。单独测试process_file函数时正常,但运行完整代码时出现以下错误:
Error in future_apply(sub_files, FUN = process_file, future.seed = TRUE) : dim(X) must have a positive length
完整代码如下:
library(tibble) library(tidyverse) library(future.apply) library(jsonlite) # JSON parsing # Set up parallel processing plan(multisession) parent_folder <- "D:/data" sub_files <- list.files(parent_folder, recursive = TRUE, full.names= TRUE) mydata_all <- data.frame() # Function to process each file process_file <- function(sub_file) { print(sub_file) # Check if the file exists and is not empty if (file.exists(sub_file) && file.info(sub_file)$size > 0) { # Read the lines from the file lines <- readLines(sub_file) # Check if the lines contain valid JSON if (all(sapply(lines, function(line) { tryCatch({ fromJSON(line) TRUE }, error = function(e) { FALSE }) }))) { # If all lines contain valid JSON, proceed with reading JSON out <- lapply(lines, fromJSON) song <- out[[1]]$mc$marketDefinition$song music_type <- out[[1]]$mc$musicDefinition$name mydata <- tibble(song = song, music_type = music_type) return(mydata) } else { # If any line doesn't contain valid JSON, handle the error print("Invalid JSON data in the file!!") return(NULL) } } else { # If the file doesn't exist or is empty, handle the error print("The file doesn't exist or is empty!!") return(NULL) } } # Process files in parallel results <- future_apply(sub_files, FUN = process_file, future.seed = TRUE) # Bind rows of non-NULL results mydata_all <- bind_rows(results[!sapply(results, is.null)])
错误原因分析
这个错误的核心是**sub_files为空列表**,也就是list.files()没有找到任何符合条件的文件。future_apply要求输入的对象必须有正长度,当输入长度为0时就会触发该错误。
具体可能的原因:
- 指定的
parent_folder路径错误,比如"D:/data"不存在,或者路径格式不符合系统要求(比如Windows下路径大小写问题、斜杠反斜杠混用) - 目标文件夹中没有文件,或者
list.files()的参数设置导致未匹配到目标压缩文件:比如需要添加pattern参数指定压缩文件后缀(如pattern = "\\.gz$"),否则可能漏掉文件;或者文件夹里只有子目录没有文件,recursive=TRUE也无法返回文件路径 - 权限问题:当前R进程没有访问该文件夹的权限,导致
list.files()无法读取到文件
建议在调用future_apply前添加检查逻辑,提前定位问题:
if (length(sub_files) == 0) { stop("未在指定文件夹中找到任何文件,请检查路径或文件是否存在!") }
内容的提问来源于stack exchange,提问作者user2165379
相关产品推荐
相关产品推荐

