简体   繁体   English

使用 R 读取多个 excel 文件中特定选项卡中的特定单元格

[英]Read specifc cells in specific tab in multiple excel files using R

I have a folder containing several excel files(both xlsm and xlsx).我有一个文件夹,其中包含几个 excel 文件(xlsm 和 xlsx)。 I have to read specific cells on each file and have that as a single row and do that for all files.我必须读取每个文件上的特定单元格并将其作为一行并为所有文件执行此操作。 When I do it for 1 file I am able to do it using this code:当我为 1 个文件执行此操作时,我可以使用以下代码执行此操作:

ClassID <- "test"
ClassDate <- read_excel("file1.xlsm", sheet = "SUMMARY", range = "E1:E1", col_names=FALSE)[[1]]
Curriculum <- read_excel("file1.xlsm", sheet = "SUMMARY", range = "C3:C3", col_names=FALSE)[[1]]
   
Summary <- cbind(ClassID,
                     ClassDate,
                     Curriculum)

But when I try to use the pattern function to read all files and use a for loop to run all files I get an error: Error in rbind2(argl[[i]], r): cannot coerce type 'closure' to vector of type 'list' .但是,当我尝试使用模式 function 读取所有文件并使用 for 循环运行所有文件时出现错误: Error in rbind2(argl[[i]], r): cannot coerce type 'closure' to vector of type 'list' When I look at the file.list object I can see that all my files are being retrieved.当我查看 file.list object 时,我可以看到正在检索我的所有文件。

file.list <- list.files(pattern = '*.xls')
df.list <- lapply(file.list, read_excel)

for (i in file.list){
ClassID <- "test"
ClassDate <- read_excel(i, sheet = "SUMMARY", range = "E1:E1", col_names=FALSE)[[1]]
Curriculum <- read_excel(i, sheet = "SUMMARY", range = "C3:C3", col_names=FALSE)[[1]]

SummaryNew <- cbind(ClassID,
                 ClassDate,
                 Curriculum)
Summary <- rbind(Summary,SummaryNew)
}

This should work:这应该有效:

library(readxl)
file.list <- list.files(pattern = '*.xls')
res <- lapply(file.list, function(x) {
    ClassID <- "test"
    ClassDate <- read_excel(x, sheet = "SUMMARY", range = "E1:E1", col_names=FALSE)[[1]]
    Curriculum <- read_excel(x, sheet = "SUMMARY", range = "C3:C3", col_names=FALSE)[[1]]
    data.frame(ClassID, ClassDate, Curriculum)
})
do.call(rbind, res)

While you could in principle use cbind and rbind , that would create a matrix with all columns coerced to character.虽然您原则上可以使用cbindrbind ,但这会创建一个矩阵,其中所有列都被强制转换为字符。 A data.frame can have columns with different classes, such as numeric, date, etc..一个data.frame可以包含具有不同类别的列,例如数字、日期等。

Here, we first create a list of data.frames and then use rbind on that to combine the list elements.在这里,我们首先创建一个 data.frames 列表,然后在其上使用rbind来组合列表元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM