Search code examples
rtidyversepurrrreadxl

Read only selective Excel workbooks into R and save them as dataframe


I have a Excel workbook with 3 sheets (sheets name = vi , hi and hh) , I want to import only sheet hi and hh and store them as a data frame.

This snippet load 3 sheets as a list

library(readxl)
library(tidyverse)

my_path <-  "my_file.xlsx"

my_path %>% 
  excel_sheets() %>% 
  set_names() %>% 
  map(read_excel, path = my_path) 

but I want to import only sheet 2 and 3 and a data frame not list so I tried this, but it returns empty tibble. What is missing here?

patterns <- c( "hi" ,   "hh")

my_path %>% 
  excel_sheets() %>% 
  set_names() %>% 
  map_dfr(patterns, ~read_excel(path = my_path))

Solution

  • You can pass the sheet names into read_excel.

    my_path <-  "my_file.xlsx"
    patterns <- c( "hi" ,   "hh")
    
    result <- map_df(patterns, ~read_excel(path = my_path, sheet = .x))