2012-06-21 55 views
1

我正在嘗試做一些我認爲應該足夠直接的東西,但到目前爲止,我一直無法弄清楚(不出意外,我是一個noob)...在R中提示用戶輸入多個文件

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

你試過?choose.files

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

choose.files是Windows規格的我相信。 – ALiX

+0

謝謝,這正是我一直在尋找的! –

+0

安裝tcltk包後,我可以在mac上使用'tk_choose.files()' –

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 
}