For-Loop读取和保存多个数据文件

时间:2016-02-08 18:05:42

标签: r for-loop

我想将相同的代码应用于大约600个单独的文件。我不能先合并所有文件,因为单个文件已经非常大。我想打开每个文件的文件,进行数据操作,保存该文件,关闭它并继续下一个文件。)

我的代码如下:

#List all files from directory (this works)
files <- list.files("path", pattern="*.TXT")

#Loop over files
for(i in 1:length(files))
{
data[i] <- read.table(files[i], header=TRUE)

data[i] <- merge(data[i], dataset, by.x="ID", all.x=TRUE) #dataset is a file containing IDs for observations I wish to select from each file (it has a variable 'dummy' that equals 1 for each ID i wish to subset)
attach(data[i])
dummy[is.na(dummy)] <- 0

data[i] <- data[i][which(dummy==1),]
write.table(data[i], "PATH/data[i].txt", sep="\t")

rm(list=ls())
}

输出 列出目录中的所有文件:

> print(files)
[1] "2729_1636_1687.TXT" "2729_1688_1739.TXT"

循环不起作用:

Error in data[i] <- read.table(files[i], header = TRUE) : 
  object of type 'closure' is not subsettable

for(i in 1:length(files))
{
data <- read.table(files[i], header=TRUE)

data <- merge(data, dataset, by.x="ID", all.x=TRUE) 
dummy[is.na(dummy)] <- 0

data <- data[which(dummy==1),]
write.table(data, paste("PATH/data[",i,"].txt"), sep="\t")

rm(data)
}

0 个答案:

没有答案