r-如何用循环绑定多个文件



我有一组30个文件,它们具有相同的变量名(所有文件都在同一目录中)的公共根名称(例如file-0001、file-0002等),我想将它们附加到主数据集。我该怎么做?

您可以尝试(如果所有文件都在同一工作目录中)

 files <- list.files(pattern="file-[0-9]+")
 res1 <- do.call(`rbind`,lapply(files, read.table, header=T))

 library(data.table) 
 rbindlist(lapply(files, fread))

使用list.files按照特定模式获取特定文件夹中的所有文件,例如:

DF <- masterDF
filePaths <- list.files(path="folderpath",pattern="file-[0-9]+",include.dirs=T)
for(filePath in filePaths){
  currentDF <- read.table(filePath)
  DF <- rbind(DF, currentDF)
}

用所有文件的名称和id创建一个表,然后写这样的东西:

#load the table with the name of the file & id
list<-read.table("Table.txt",header=T)
#define the range
i=max(list$id)+1
#make the loop
while (i>0)
i=i-1
#select the name of your file from the table
for(i in 1:length(list[,1])) {if (list[i,1]==id) {file<-list[i,2]} }
file
#set work directory
setwd(your directory)
#use your function
result<-rbind(file)

将算法更改为您自己的工作!

最新更新