在R中提示用户输入多个输入文件

时间:2012-06-21 23:30:57

标签: r import rbind

我试图做一些我认为应该直截了当的事情,但到目前为止我一直无法弄明白(不出意外地我不是这样)...

我希望能够在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

2 个答案:

答案 0 :(得分:2)

您是否尝试过?choose.files

Use a Windows file dialog to choose a list of zero or more files interactively. 

答案 1 :(得分:1)

如果您愿意输入每个文件名,为什么不循环遍历所有文件:

filenames <- c("file1", "file2", "file3")
filecontents <- lapply(filenames, function(fname) {<insert code for reading file here>})
bigfile <- do.call(rbind, filecontents)

如果您的代码必须是交互式的,您可以在循环中使用readline函数,当用户输入空行时,该循环将停止询问更多文件:

getFilenames <- function() {
    filenames <- list()
    x <- readline("Filename: ")
    while (x != "") {
        filenames <- append(filenames, x)
        x <- readline("Filename: ")
    }
    filenames
}