我必须将多个具有随机名称的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, 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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句