循环遍历目录中的所有文件,读取并将它们保存在对象R中

时间:2015-01-12 22:08:57

标签: r

我需要遍历目录中的所有文件,读取并将它们保存在具有相同名称的对象中。

我尝试了以下但没有一个工作:

files <- list.files(path=".", pattern="*.txt", all.files=T, full.names=T)

lapply(files, function(x) {
t <- read.table(x, header=F)  
out_x <- function(t)            
})

path = "."
out.file<-""
file.names <- dir(path, pattern ="*.txt") 
for(i in 1:length(file.names)){
file <- read.table(file.names[i],header=TRUE)
out.file <- rbind(out.file, file)
} 

1 个答案:

答案 0 :(得分:1)

library(tools)

files <- list.files(path=".", pattern="*.txt", all.files=T, full.names=T)

以下代码部分来自How can I ask a user and read those files(s) into separate dataframes?

filelist <- lapply(files, read.table, header=F)
names(filelist) <- paste0(basename(file_path_sans_ext(files)))
list2env(filelist, envir=.GlobalEnv)

以下代码部分来自Storing multiple data frames into one data structure - R

lapply(names(filelist), function(u) {
assign(u, filelist[[u]]) 
save(list=u, file=paste0(u, ".Rdata"))
})