0
我的工作目錄中有一個文件夾,其中包含15個分隔文本文件(1686 * 2矩陣)。我想創建一個文件列表,然後讓R訪問這些文件,這樣我就可以將每個文件導入R.我嘗試使用dir()函數,但列表似乎捕獲文件的名稱作爲字符並且不能訪問內容文件。請幫我解決一下這個。謝謝在R中創建一個文件列表,然後形成一個矩陣追加第二列
我的工作目錄中有一個文件夾,其中包含15個分隔文本文件(1686 * 2矩陣)。我想創建一個文件列表,然後讓R訪問這些文件,這樣我就可以將每個文件導入R.我嘗試使用dir()函數,但列表似乎捕獲文件的名稱作爲字符並且不能訪問內容文件。請幫我解決一下這個。謝謝在R中創建一個文件列表,然後形成一個矩陣追加第二列
dir()只是給你一個向量與文件。您需要使用read.table()並遍歷目錄,例如如下:
# this is subdirectory where I put the test files
setwd("./csv")
# this gets a vector containing all the filenames
myfiles<-dir()
# this loops through the length of the vector (i.e. number of files)
for(i in 1:length(myfiles)){
# this reads the data (my test file has only 4 columns, no header and is csv (use "\t" for tab))
fileData<-read.table(file=myfiles[i],header=FALSE,sep=",",col.names=c("A","B","C","D"))
# if the target table doesn't exist create it, else append
ifelse(exists("targetTable"),targetTable<-rbind(targetTable,fileData),targetTable<-fileData)
}
head(targetTable)
希望有幫助!