如何使用具有特定行和列的循环在 R 中读取多个 xlsx 文件

How to read multiple xlsx file in R using loop with specific rows and columns

我必须将多个具有随机名称的 xlsx 文件读入单个数据帧。每个文件的结构是相同的。我必须只导入特定的列。

我试过这个:

dat <- read.xlsx("FILE.xlsx", sheetIndex=1, 
                  sheetName=NULL, startRow=5, 
                  endRow=NULL, as.data.frame=TRUE, 
                  header=TRUE)

但这一次只针对一个文件,我无法指定我的特定列。 我什至试过了:

site=list.files(pattern='[.]xls')

但在那个循环之后就不起作用了。怎么做?提前致谢。

我会把每个 sheet 读到一个列表中:

获取文件名:

f = list.files("./")

读取文件:

dat = lapply(f, function(i){
    x = read.xlsx(i, sheetIndex=1, sheetName=NULL, startRow=5,
        endRow=NULL, as.data.frame=TRUE, header=T)
    # Get the columns you want, e.g. 1, 3, 5
    x = x[, c(1, 3, 5)]
    # You may want to add a column to say which file they're from
    x$file = i
    # Return your data
    x
})

然后您可以通过以下方式访问列表中的项目:

dat[[1]]

或者对他们执行相同的任务:

lapply(dat, colmeans)

将它们变成数据框(您的文件列现在在这里变得有用):

dat = do.call("rbind.data.frame", dat)

我比较熟悉for循环,会比较麻烦一点。

filelist <- list.files(pattern = "\.xlsx") # 列出目录中的所有 xlsx 文件

allxlsx.files <- list()  # create a list to populate with xlsx data (if you wind to bind all the rows together)
count <- 1
for (file in filelist) {
   dat <- read.xlsx(file, sheetIndex=1, 
              sheetName=NULL, startRow=5, 
              endRow=NULL, as.data.frame=TRUE, 
              header=TRUE) [c(5:10, 12,15)] # index your columns of interest
   allxlsx.files[[count]] <-dat # creat a list of rows from xls files
   count <- count + 1
}

转换回 data.frame

allfiles <- do.call(rbind.data.frame, allxlsx.files)

对于 Wyldsoul 的答案的变体,但在同一 Excel 文件中跨多个 Excel 工作表(在 1 和 j 之间)使用 for 循环,并与 dplyr 绑定:

library(gdata) 
library(dplyr)

for (i in 1:j) {
  dat <- read.xls(f, sheet = i) 
  dat <- dat[,1:14] # index your columns of interest
  allxlsx.files[[count]]
  count <- count + 1
}

allfiles <- do.call(bind_rows, allxlsx.files)