我有一个包含大约50,000个文本文件的文件夹。我只想读入大约6,000个这样的文件,这取决于文件的名称。所有文件的编号为5.txt、16.txt等。
这是我的尝试:
library(plyr)
library(qpcR)
files.content <- list.files("~/RFiles/user", "*.txt", full.names=T)
ID <- as.character(unique(ratings.df$RID))
# take the ID from a column of a dataframe further down in script
# [1] "18617" "31213" "31203" "14975" "14749" "31192" etc
read.data <- function(x) {
num <- as.numeric(gsub("[^\\d]", "", x, perl=T))
# gives me a list of numbers from folder
select.files <- if(num %in% ID) {
x1 <- file(x, open="rt")
x2 <- readLines(x1, warn=F, encoding="UTF-8")
x3 <- c(num, x2)
}
}
table.files <- lapply(files.content, read.data)
temp.vec <- do.call(qpcR:::rbind.na, table.files)
table.df <- data.frame(temp.vec, stringsAsFactors=F)有人有更好的建议吗?由于某种原因,它仍然将50,000个文件读入数据帧,而不是所选的6,000个文件。
修改:把10,000改回50,000。
发布于 2014-09-24 03:48:12
在运行lapply中的函数之前,设置要读取的文件的子集。我猜do.call中的rbind.na正在读取额外的44k文件上的lapply生成的一个空白元素,并固定在所有的NA中。
# create similar matching scenario
files <- paste0(1:200,'.txt')
id <- sample(files,50,replace = F)
id <- gsub('\\.txt','',id)
# subset the files needed; change regex to your case
index <- sub('[^0-9]*([0-9]{1,5})\\.txt','\\1',files) %in% id
filestoread <- files[index]
# however you need to read in, this is not tested
table.files <- lapply(filestoread,readLines,open = file(x, open="rt"),warn = F,encoding = "UTF-8")
# end with do.call and data.frame顺便说一句,我浏览了rbind.na文档,它似乎给了您一堆额外的NA行,使每个数据帧大小相同。例如,rbind.na两个10行和1000行的data.frames,最终将得到1010行数据和990行NA。常规的rbind只会给你1010个数据,这通常是你需要的。在您的示例中,这是6k data.frames的数据,44k data.frames的所有NA,每个大小相当于您最大的文件大小。rbind可能也会跳过原始代码中的空白元素。
https://stackoverflow.com/questions/22487667
复制相似问题