【发布时间】:2012-06-21 23:30:57
【问题描述】:
我正在尝试做一些我认为应该直截了当的事情,但到目前为止我一直无法弄清楚(毫不奇怪,我是个菜鸟)...
我希望能够在 R 中提示用户输入文件。我已成功使用 file.choose() 获取单个文件,但我希望可以选择多个文件一次。
我正在尝试编写一个程序来吸收每日数据文件,具有相同的标题并将它们附加到一个大的月度文件中。我可以通过单独导入文件,然后使用rbind(file1, file2,...) 在控制台中完成此操作,但我需要一个脚本来自动化该过程。每次运行之间要追加的文件数量不一定是恒定的。
谢谢
更新:这里是我想出的适合我的代码,也许它对其他人也有帮助
library (tcltk)
File.names <- tk_choose.files() #Prompts user for files to be combined
Num.Files <-NROW(File.names) # Gets number of files selected by user
# Create one large file by combining all files
Combined.file <- read.delim(File.names [1], header=TRUE, skip=2) #read in first file of list selected by user
for(i in 2:Num.Files){
temp <- read.delim(File.names [i], header=TRUE, skip=2) #temporary file reads in next file
Combined.file <-rbind(Combined.file, temp) #appends Combined file with the last file read in
i<-i+1
}
output.dir <- dirname(File.names [1]) #Finds directory of the files that were selected
setwd(output.dir) #Changes directory so output file is in same directory as input files
output <-readline(prompt = "Output Filename: ") #Prompts user for output file name
outfile.name <- paste(output, ".txt", sep="", collapse=NULL)
write.table(Combined.file, file= outfile.name, sep= "\t", col.names = TRUE, row.names=FALSE)` #write tab delimited text file in same dir that original files are in
【问题讨论】: