2010-08-03 485 views
13

我正在使用R可視化一些數據,所有這些數據都是.txt格式。目錄中有幾百個文件,我想一次性將它加載到一張表中。如何將多個.txt文件讀入R?

任何幫助?

編輯:

列出文件不是問題。但是我從列表到內容都遇到了麻煩。我已經嘗試了一些代碼從here,但我得到一個錯誤與此部分:

all.the.data <- lapply(all.the.files, txt , header=TRUE) 

Error in match.fun(FUN) : object 'txt' not found 

的代碼片段任何會澄清這個問題,將不勝感激。

+0

問題是'txt'不是函數。您指向的鏈接是關於'read.csv'函數的。感謝 – Wok 2010-08-03 17:56:58

回答

4

感謝所有的答案!

與此同時,我也自己砍了一種方法。讓我知道,如果它是任何有用的:

library(foreign) 

setwd("/path/to/directory") 

files <-list.files() 

data <- 0 


for (f in files) { 

tempData = scan(f, what="character") 

data <- c(data,tempData)  

} 
4

看功能dir()又名list.files()的幫助。這可以讓你得到一個文件列表,可能通過正則表達式過濾,你可以通過它循環。

如果您想一次全部使用它們,您首先必須在一個文件中包含內容。一種選擇是使用cat鍵入所有文件到stdout並閱讀使用popen()。有關更多信息,請參閱help(Connections)

+0

,但仍不清楚。檢查我的編輯:) – 2010-08-03 15:23:54

+0

那麼,創建'txt'。 – 2010-08-03 15:32:33

25

你可以試試這個:

filelist = list.files(pattern = ".*.txt") 

#assuming tab separated values with a header  
datalist = lapply(filelist, function(x)read.table(x, header=T)) 

#assuming the same header/columns for all files 
datafr = do.call("rbind", datalist) 
+0

稍微更清潔:'lapply(filelist,FUN = read.table,header = TRUE)' – RockScience 2015-04-16 09:10:53

2

有一個非常,非常簡單的方法,現在做到這一點:READTEXT包。

readtext::readtext("path_to/your_files/*.txt") 

真的那麼容易。

0

有兩個快速的方法來讀取多個文件,並把它們放在一個單獨的數據幀或data.table

使用freaddata.table

# List all txt files including sub-folders 
    list_of_files <- list.files(path = ".", recursive = TRUE, 
          pattern = "\\.txt$", full.names = TRUE) 

    library(data.table) 

    # Read all the files and create a FileName column to store filenames 
    DT <- rbindlist(sapply(list_of_files, fread, simplify = FALSE), 
         use.names = TRUE, idcol = "FileName") 

使用purrr::map_dfreadr::read_table2tidyverse包:

library(tidyverse) 

    # Read all the files and create a FileName column to store filenames 
    df <- list_of_files %>% 
    set_names(.) %>% 
    map_df(read_table2, .id = "FileName") 

注意:要清理文件名,請使用basenamegsub函數