【发布时间】:2014-08-29 17:38:09
【问题描述】:
我有一组 30 个具有通用根名称的文件(例如 file-0001、file-0002 等),它们具有相同的变量名称(同一目录中的所有文件),我想附加到主数据集。我该怎么做?
【问题讨论】:
我有一组 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)
将算法更改为您自己的工作!
【讨论】: