[英]import large number of .txt files to data.frame, include empty .txt files by giving them a row data.frame
[英]How can I read different .txt files in R but not join them in the same data.frame?
我需要從一個文件夾中將許多.txt
文件讀入數據幀。 .txt
文件名的格式為angles_*_dat.result
(例如angles_1_dat.result
, angles_2_dat.result
)。
我正在使用這個,但是看起來是“新手”:
data1 <- read.table("~/data/angles_medias_1.dat.results.dat.", quote="\"", comment.char="")
data2 <- read.table("~/data/angles_medias_2.dat.results.dat.", quote="\"", comment.char="")
data3 <- read.table("~/data/angles_medias_3.dat.results.dat.", quote="\"", comment.char="")
data4 <- read.table("~/data/angles_medias_4.dat.results.dat.", quote="\"", comment.char="")
data5 <- read.table("~/data/angles_medias_5.dat.results.dat.", quote="\"", comment.char="")
data6 <- read.table("~/data/angles_medias_6.dat.results.dat", quote="\"", comment.char="")
data7 <- read.table("~/data/angles_medias_7.dat.results.dat", quote="\"", comment.char="")
data8 <- read.table("~/data/angles_medias_8.dat.results.dat", quote="\"", comment.char="")
data9 <- read.table("~/data/angles_medias_9.dat.results.dat", quote="\"", comment.char="")
data10 <- read.table("~/data/angles_medias_10.dat.results.dat", quote="\"", comment.char="")
還有其他方法(例如循環)將所有數據文件加載到不同的數據幀中嗎?
編輯:
例如數據:
V1 V2 V3 V4 V5 V6 V7 V8 V9
100 0 100 100 0 100 100 100 100
100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100
您可以將它們全部讀入列表。 可以說,這比破解全局名稱空間更干凈。
files <- dir(directory, pattern = ".txt") # directory is the path to the directory containing the files
dframes <- lapply(files, read.table, quote="\"", comment.char="")
然后,您可以訪問列表中的數據幀,例如,第一個df的dframes[[1]]
。 如果您更喜歡$
訪問語法:
names(dframes) <- sapply(as.character(1:length(files)), function(i) paste("df", i, sep=""))
現在您可以訪問與dframes$df1
相同的數據幀
使用lapply
:
allTextFiles <- list.files(pattern = ".txt")
alldfs <- lapply(allTextFiles, function(x) {
textfiles <- read.table(x, quote="\"", comment.char="")
})
alldfs <- lapply(x = alldfs, seq_along(alldfs), function(x, i) {
assign(paste0("data", i), x[[i]], envir=.GlobalEnv)
})
這樣的事情應該可以解決問題:
files_to_read <- dir(pattern = ".txt") # make sure only the files you want to read are in this dir
n <- 0
for(i in 1:length(files_to_read)){
assign(paste("df",n,sep=""), read.table(files_to_read[i], quote="\"", comment.char=""))
n <- n+1
}
如果您不想在該目錄中導入.txt
文件,則可以僅使用要導入的.txt
文件創建一個新目錄,也可以進一步自定義pattern
以僅匹配要導入的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.