【问题标题】:Prompting user for multiple input files in R提示用户在 R 中输入多个输入文件
【发布时间】: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

【问题讨论】:

    标签: r import rbind


    【解决方案1】:

    你试过?choose.files

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

    【讨论】:

    • choose.files 我相信是特定于 Windows 的。
    • 谢谢,这正是我要找的!
    • 安装 tcltk 包后我可以在 mac 上使用tk_choose.files()
    【解决方案2】:

    如果您愿意键入每个文件名,为什么不像这样遍历所有文件:

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-30
      • 2016-09-26
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多