如何将多个xlsx文件读入R,然后将它们存储为以xlsx文件名称标记的单独列表?

我有一个文件夹与众多的xlsx文件,都需要以完全相同的方式格式化。 我想将它们读入R中,并将它们存储为可以使用xlsx文件名引用的列表,以便通过格式化代码提供。 这是我发现的基于for循环中迭代值的代码。

library("xlsx") library("gdata") library("rJava") setwd("C:/Users/Owner/Desktop/FolderDatabase") getwd() files = list.files(pattern = "\\.xlsx") #View(files) dfList <- list() for (i in seq_along(files)){ dfList[[paste0("excel",i)]] <- read.xlsx(files[i], sheetIndex = 1) } # Calling the xlsx lists that were created from the directory dfList$excel1 dfList$excel2 dfList$excel3 dfList$excel4 

如果xlsx文件被命名为myname1.xlsx,我希望列表被命名为myname1。

而不是初始化dfList为空,请尝试非for方法:

 dfList <- lapply( files, read.xlsx, sheetIndex = 1) names(dfList) <- gsub("^.+/|\\.xlsx", "", files) 

要不就:

 dfList <- sapply( files, read.xlsx, sheetIndex = 1) 

这两个部分模式的第一部分是在那里,因为我通常与完整的文件规格,虽然在你的情况下,可能不需要。 “OR”(“|”)的第二部分是必需的。