R: Use Regex to Import Specific Sheets from Multiple Excel Files

笑着哭i 提交于 2021-02-10 15:57:02

问题


I have a group of Excel files with multiple sheets which don’t follow a standard naming convention. I want to create a single data frame from specific sheets containing the keyword 'frame'.

library(tidyverse)
library(openxlsx)

# Sample Excel File 1
df1 <- data.frame(replicate(10,sample(0:1,10,rep=TRUE)))
data_frame2 <- data.frame(replicate(10,sample(0:1,10,rep=TRUE)))
list_of_datasets1 <- list("df" = df1, "date_frame" = data_frame2)
write.xlsx(list_of_datasets1, file = "writeXLSX1.xlsx")

# Sample Excel File 2
df3 <- data.frame(replicate(10,sample(0:1,10,rep=TRUE)))
data_frame4 <- data.frame(replicate(10,sample(0:1,10,rep=TRUE)))
list_of_datasets2 <- list("date_frames" = df3, "dfs" = data_frame4)
write.xlsx(list_of_datasets2, file = "writeXLSX2.xlsx")

# Create List of Excel Files
excel_file_list <- list.files(pattern = "writeXLSX\\d*.xlsx", full.names = T)

I'd like to be able to do this using a regex with purr like this:

df_bind <- excel_file_list %>%
  map_dfr(~read_excel(.x, sheet = grepl("frame", .x)))

The closest answer I found works fine with a single file. However, I can't quite figure out how to extract the sheet names correctly when they're in a list.


回答1:


We can use str_detect

library(readxl)
library(dplyr)
library(purrr)
excel_file_list %>% 
      map_dfr(~ read_excel(.x, sheet = which(str_detect(excel_sheets(.x), 'frame'))))


来源:https://stackoverflow.com/questions/61308709/r-use-regex-to-import-specific-sheets-from-multiple-excel-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!