2016-11-10 54 views
0

我是R新手。我嘗試處理一些實驗數據,並在讀取文件時遇到了一個錯誤。 我想讀取文件夾中的一些數據文件,但我不知道有多少。我只知道所有文件都被命名爲「Subject1ManualX.log」,X爲1或更高。由於我沒有發現計算文件夾中有多少文件的可能性,我嘗試在while循環中打開文件,直到引發異常(即,我嘗試打開「Subject1Manual1.log」,然後是「Subject1Manual2.log」等等)。R - 讀未知數量的文件

這裏是我的代碼(版畫是用於調試):

# Script to work on ET data 
temp <- 0 

while (temp == 0){ 
    tryCatch({ 
    subjectData <- read.delim("D:/Doctorat/XPs/XP1-2_LIPSMWA/SmartEye/Subject1/Subject1Manual3.log") 

    }, warning = function(w){ 
    print(paste("warning", i)) 
    temp <- 1 

    }, error = function(e){ 
    print(paste("error", i)) 
    temp <- 1 

    }, finally = { 
    print("finished") 
    }) 
} 

遺憾的是它不工作(這就是爲什麼我在這裏...)。我知道我會有警告和錯誤。如果我處理警告,R會因爲錯誤未處理而崩潰(「所有連接正在使用」崩潰)。如果我只處理錯誤,它不會通過它並且while循環在每次迭代中繼續。

任何關於這個問題的想法都將被高度讚賞(包括更好的方法來讀取未知數量的文件)。感謝您的時間!

Pyxel

編輯:確定了一些不錯的人回答如何導入多個數據文件,但出於好奇,我想知道如何處理while循環內嘗試捕捉。任何想法?

+0

使用'list.files'函數來獲取所有文件,用戶'pattern'選擇特定文件......這可以用在for循環或曾經怎樣處理它們容易..... – drmariod

回答

1
# Here we read path to all '*.log' files in folder 
path_to_files = dir("D:/Doctorat/XPs/XP1-2_LIPSMWA/SmartEye/Subject1/", 
        full.names = TRUE, 
        recursive = TRUE, 
        pattern = "\\.log$") 

# further we read all files to list 
files = lapply(path_to_files, read.delim) 

# and finaly we combine files to single data.frame 
# headers of files should be identical 
res = do.call(rbind, files) 

UPDATE代碼tryCatch和時間。這是不安全的,它增加了循環中的data.frame - 這是不好的做法。

subjectData = TRUE 
i = 1 
res = NULL 
while (!is.null(subjectData)){ 
    subjectData <- tryCatch({ 
     read.delim(sprintf("D:/Doctorat/XPs/XP1-2_LIPSMWA/SmartEye/Subject1/Subject1Manual%s.log", i)) 

    }, warning = function(w){ 
     print(paste("warning", i)) 
     NULL 

    }, error = function(e){ 
     print(paste("error", i)) 
     NULL 

    }) 
    if(is.null(res)){ 
     res = subjectData 
    } else { 
     res = rbind(res, subjectData) 
    } 
    i = i + 1 
} 
+0

謝謝你,我想我使用了錯誤的關鍵字來找不到這個「dir」函數。我試過你的解決方案,它完美的作品。 任何想法,但如何處理while循環trycatch? – Pyxel

+0

@Pyxel查看更新。但我不建議使用此代碼。 –

+0

>非常感謝您的幫助!我不會使用它,因爲你的第一個解決方案絕對更清潔,但我很好奇如何解決我最初的問題。 – Pyxel