首页 > 解决方案 > 使用 R 和 Tidyverse,如何从多个 Excel 工作簿中导入同一种工作表

问题描述

我有多个工作簿,其中包含相同数量的工作表、工作表名称和数据。我将如何从每个工作簿中导入特定的工作表?例如,假设我只想从每个工作簿中导入“结果”选项卡的特定部分。我只想从 B11:V11 列(所有工作表的常量)导入数据,但是每个工作簿的每个列的末尾都是动态的。谢谢你的帮助。

标签: r

解决方案


尝试使用以下代码:

FILES <- dir(pattern = ".xslx$")

# Make a function in order to get the data in range from "Result tab"
read_range <- function(excel_file,range_="B11:V11"){
  sheets <- excel_sheets(excel_file)
  # Assuming that there's always a "Result" tab
  # and only one tab with this name
  sheet_id <- grep("Result",sheets)
  return(read_excel(excel_file,col_names= FALSE,sheet=sheet_id,range=range_))
} 

# Iterate in sheets vector 
data <- lapply(FILES,read_range)

# `data` is a list, yo can get the dataframe with rbind
df <- do.call("rbind",data)

希望这可以帮助


推荐阅读