首页 > 解决方案 > R-用循环读取excel文件并创建数据框

问题描述

我有一堆文件(数量不断增长),每个文件都应该有一个单独的数据框。

为了简化阅读,我想使用循环来读取所有文件。新数据框应以“文件名”中的字符串命名

在最后一行我想创建一个数据框,新数据框的名称应该是“文件名”的内容。

for(x in 1:nrow(Namen)) # creation of the loop

{

  Filename<- Namen[x,1] #Takes the Filename from the the DF

  einlesepfad <- "path for reading the xlsm files" 
   einlesepfad <- paste(einlesepfad,Filename,".xlsm", sep="") # creation of the path to read the xlsm file
   Filename <- read_excel(einlesepfad) #The Content of "Filename" should be the Name of the new data frame
}

标签: rloopsdataframe

解决方案


如果我理解正确,您想将列表中的许多文件读入单个数据帧吗?我提供了一个稍微不同的解决方案:

results <- list()
for(x in 1:nrow(Namen)) # creation of the loop
{
  Filename<- Namen[x,1] #Takes the Filename from the the DF

  einlesepfad <- "path for reading the xlsm files" 
  einlesepfad <- paste(einlesepfad,Filename,".xlsm", sep="") # creation of the path to read the xlsm file
  results[Filename] <- read_excel(einlesepfad) # The list gets a new item, named whatever value Filename had, that contains your data
}

这样,您的每个文件都在一个单独的数据框中,并且所有数据框都在一个列表中 - results。要从文件访问数据框,"datafile1.xlsm"请执行以下操作:

results['datafile1']

甚至

results$datafile1

您之前尝试做的是为每个数据框提供一个单独的变量- 可能(我认为您可以使用paste然后构造语句eval),但数据框列表几乎总是一个更好的主意。


推荐阅读