Import multiple sheets from excel spreadsheet into r

谁说我不能喝 提交于 2021-02-05 11:49:58

问题


I want to import multiple sheets, selected by a common string in the sheet name, from a single .xlsx file and concatenate them into single data frame. For example, if I have an excel file ('data.xlsx') with worksheets named samples1, samples2, samples3, controls1, controls2, controls3. I want to make a list of the worksheet names, such as:

sheet_list <- lapply(excel_sheets('data.xlsx'), read_excel, path = 'data.xlsx')

Then, I want to import all sheets that contain 'samples' in the name and bind them into a data frame called 'samples'. How can I accomplish this efficiently?


回答1:


You are very close! You can use lapply and such to accomplish this using base R, but I routinely perform tasks like this using the purrr package.

library(purrr)
library(readxl)    

sheets <- excel_sheets('data.xlsx')

sample_sheets <- sheets[grepl("samples", sheets)]

sheet_df <- map_dfr(sample_sheets, ~read_excel(path = 'data.xlsx', sheet = .x, id = .x))

This does:

  1. Get the names of the sheets.
  2. Use grepl to subset the sheets to only those containing "samples" in the name.
  3. Use map_dfr to iterate over the sample sheets, reading each one in and assigning an id column equal to the name of the sheet, then bind all the results together by rows and return a data frame.



回答2:


Does this do what you want?

path <- "C:\\your_path_here\\test.xlsx"

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



回答3:


Try this

library(readxl)
list <- excel_sheets("path_to_excel.xlsx")
list_samples <- list[grepl("samples", list)]
df <- rbind(lapply(list_samples, function(x) read_excel("path_to_excel.xlsx", sheet = x)))


来源:https://stackoverflow.com/questions/49925164/import-multiple-sheets-from-excel-spreadsheet-into-r

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