从目录中读取多个文件

时间:2019-01-22 01:26:22

标签: r file loops

我将.DAT文件放在一个变量中。我想创建一个循环,将读取每个“;”在数据框中分离文件,并在遍历列表时将所有文件合并到数据框中。

因此,alldata [[1 ..]]可以查看文件。

The content of the list

现在有人建议可以循环访问列表并读取.DAT文件的循环(sep =“;”)

2 个答案:

答案 0 :(得分:1)

正在读取所有文件,但是每次都将信息覆盖到data.2002上,因此最后您只能看到最终文件。您需要首先在循环末尾使用索引将所有数据放入列表中。

编辑:如下面的尼克所述,您的file.type变量(应称为file_list或其他名称)应具有文件的实际长度,否则可能会下标错误(添加了一些类似的代码)

files <- list.files(path_to_your_folder, pattern = ".dat", recursive = TRUE, include.dirs = FALSE)

data.2002 <- list()
counter <- 1

for(i in files) {

   tempFile < -read.delim(file.path(path_to_your_folder, i)))
   ...
   <Here your modifications to tempFile>
   ...
  data.2002[[counter]] <- tempFile
  counter <- counter + 1

}

然后,您可以随后绑定具有at least a couple of ways的行:

df <- do.call("rbind", listOfDataFrames)

dplyr::bind_rows(list_of_dataframes, .id = "column_label")

答案 1 :(得分:0)

您也可以尝试遍历目录中的所有文件。

# Read all of the DAT files in the directory. 
# Ensure there are only the DAT files you need in there.
temp <- list.files(YOUR_DIRECTORY, pattern = "*.dat", full.names = TRUE)

# Create an empty data frame for the data.
# Change ncol to suit the number of cols you have).
outputs.df <- data.frame(matrix(NA, nrow = 1, ncol = 10))

# Import the dat data files from your "YOUR_DIRECTORY" location
for(i in 1:length(temp)){

    # Read in each DAT file
    myfiles <-read.delim(temp[i], 
        header=FALSE, skip=0, sep=";") # change skip=X to ignore the first X rows as required.

    # Ensure column names are identical
    names(outputs.df) <- names(myfiles)
    # bind the rows
    outputs.df <- rbind(outputs.df, myfiles)
}
    # Remove the first row as it contains NA values
    outputs.df <- outputs.df[-1,]
相关问题