以下脚本将首先创建仅包含列名的文件,然后附加每个结果。
filename <- system("ls /dir/",intern=TRUE)
column_names <- data.frame(filename = "filename", mean = "mean")
write.table(column_names, file = "output.csv", row.names = FALSE,
append = FALSE, col.names = FALSE, sep = ", ", quote = TRUE)
for(i in 1:length(filename)){
file <- read.table(filename[i],header=FALSE)
newline <- data.frame(t(c(filename[i], mean(as.numeric(file$V4)))))
write.table(newline, file = "output.csv", row.names = FALSE,
append = TRUE, col.names = FALSE, sep = ", ")
}
但是,在每个步骤中写入文件的效率不是很高,您可能会考虑仅在最后执行此操作:
filename <- system("ls /dir/",intern=TRUE)
results <- data.frame(filename = "filename", mean = "mean")
for(i in 1:length(filename)){
file <- read.table(filename[i],header=FALSE)
newline <- data.frame(t(c(filename = filename[i], mean = mean(as.numeric(file$V4)))))
results <- rbind(results, newline)
}
write.table(results, file = "output.csv", row.names = FALSE,
append = FALSE, col.names = TRUE, sep = ", ")