1

我正在尝试做一些我认为应该足够直截了当的事情,但到目前为止我一直无法弄清楚(毫不奇怪,我是一个菜鸟)......

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

2 回答 2

2

你有没有尝试过?choose.files

Use a Windows file dialog to choose a list of zero or more files interactively. 
于 2012-06-21T23:41:49.307 回答
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
}
于 2012-06-22T00:01:22.413 回答