簡體   English   中英

R:使用正則表達式從多個 Excel 文件中導入特定工作表

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

我有一組 Excel 文件,其中包含多個不遵循標准命名約定的工作表。 我想從包含關鍵字'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)

我希望能夠使用帶有purr的正則表達式來做到這一點,如下所示:

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

我找到的最接近的答案適用於單個文件。 但是,當它們在列表中時,我不太清楚如何正確提取工作表名稱。

我們可以使用str_detect

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM