如何在R中使用具有特定行和列的循环读取多个xlsx文件
我必须读取具有随机名称的多个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')
但之后循环不起作用。 怎么做? 提前致谢。
我会阅读每个表到一个列表:
获取文件名称:
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, eg 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文件中使用for循环跨多个Excel工作表(1和j之间),并与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)