r - For-Loop to read and save multiple data files -
i apply same code around 600 separate files. cannot first merge files, individual files large. open file per file, data manipulations, save file, close , go on next file).
my code following:
#list files directory (this works) files <- list.files("path", pattern="*.txt") #loop on 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 file containing ids observations wish select each file (it has variable 'dummy' equals 1 each id wish 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()) } output listing files directory works:
> print(files) [1] "2729_1636_1687.txt" "2729_1688_1739.txt" the loop not work:
error in data[i] <- read.table(files[i], header = true) : object of type 'closure' not subsettable solution
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) }
Comments
Post a Comment