如何在 R 中读取不同的.txt文件,但不将它们连接到同一个 data.frame 中



我需要从一个文件夹中将许多.txt文件读取到数据帧中。.txt文件名的形式为 angles_*_dat.result(例如 angles_1_dat.resultangles_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

使用 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 <- dir(directory, pattern = ".txt")  # directory is the path to the directory containing the files
dframes <- lapply(files, read.table, quote=""", comment.char="")

然后,您可以访问列表中的数据帧,例如 dframes[[1]]第一个 df。如果您更喜欢$访问语法:

names(dframes) <- sapply(as.character(1:length(files)), function(i) paste("df", i, sep=""))

现在,您可以访问与dframes$df1相同的数据帧

这样的事情应该可以解决问题:

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以仅匹配要导入的文件。

最新更新