2012-08-07 121 views
0

我對R有點新,並且對我正在編寫的程序有疑問。我希望能夠用一個while循環(最終使用每個read.table)接收文件(與用戶一樣多),但它一直在打斷我。 這是我到目前爲止有:R:雖然循環輸入

cat("Please enter the full path for your files, if you have no more files to add enter 'X': ") 
fil<-readLines(con="stdin", 1) 
cat(fil, "\n") 
while (!input=='X' | !input=='x'){ 
inputfile=input 
input<- readline("Please enter the full path for your files, if you have no more files to add enter 'X': ") 
} 
if(input=='X' | input=='x'){ 
exit -1 
} 

當我運行它(從命令行(UNIX))我得到這些結果:

> library("lattice") 
> 
> cat("Please enter the full path for your files, if you have no more files to add enter 'X': ") 
Please enter the full path for your files, if you have no more files to add enter 'X': > fil<-readLines(con="stdin", 1) 
x 
> cat(fil, "\n") 
x 
> while (!input=='X' | !input=='x'){ 
+ inputfile=input 
+ input<- readline("Please enter the full path for your files, if you have no more files to add enter 'X': ") 
+ } 
Error: object 'input' not found 
Execution halted 

我不太知道如何解決這個問題,但我很確定這可能是一個簡單的問題。 有什麼建議嗎? 謝謝!

+1

@ttmaccer:您應該將其寫爲答案 – 2012-08-07 14:31:32

+0

您可以嘗試使用'choose.files' – James 2012-08-07 14:33:27

+0

@James您是否知道我可以找到如何使用choose.file的示例的地方? – Stephopolis 2012-08-07 14:34:55

回答

3

當你第一次運行腳本輸入不存在。指定

input<-c() 

您while語句之前說還是把 inputfile=input 下面input<- readline....

+0

非常感謝!我知道這將是一個非常愚蠢的問題,但我很困擾它。 – Stephopolis 2012-08-07 14:36:10

1

我不太確定的根本問題是什麼,您的問題。可能是因爲你輸入的目錄路徑不正確。

這是我用過幾次的解決方案。它使用戶更容易。基本上,您的代碼不需要用戶輸入,它只需要爲文件命名。

setwd("Your/Working/Directory") #This doesn't change 
filecontents <- 1 
i <- 1 
while (filecontents != 0) { 
    mydata.csv <- try(read.csv(paste("CSV_file_",i,".csv", sep = ""), header = FALSE), silent = TRUE) 
    if (typeof(mydata.csv) != "list") { #checks to see if the imported data is a list 
     filecontents <- 0 
    } 
    else { 
     assign(paste('dataset',i, sep=''), mydata) 
     #Whatever operations you want to do on the files. 
     i <- i + 1 
    } 
} 

正如你所看到的,對於這些文件的命名約定是CSV_file_n其中n是任意數量的輸入文件(我把這個代碼了我的計劃,我在其中加載CSV的之一)。當我的代碼查找一個不存在的文件時,我一直存在的問題之一是Error消息彈出。通過這個循環,這些消息不會出現。如果它將不存在文件的內容分配給mydata.csv,則僅檢查mydata.csv是否爲列表。如果是,它會繼續運行。如果不是,則停止。如果您擔心在代碼中區分來自不同文件的數據,只需將文件的相關信息插入文件本身的一個常量位置即可。例如,在我的csv中,我的第三列總是包含從其中收集csv其餘部分中包含的信息的圖像的名稱。

希望這可以幫助你一點,即使我看到你已經有一個解決方案:-)。如果你希望你的程序更加自主,這真的只是一個選擇。

+1

這是可愛的,我不確定我是否可以使用它與這個特定的程序,但我很高興看到不同的方式來獲取文件。謝謝! – Stephopolis 2012-08-07 14:53:29