将 excel 电子表格中的多张工作表导入 r
Import multiple sheets from excel spreadsheet into r
我想从单个 .xlsx 文件导入多个 sheet,由 sheet 名称中的公共字符串选择,并将它们连接到单个数据框中。例如,如果我有一个 excel 文件 ('data.xlsx'),其中 worksheets 名为 samples1、samples2、samples3、controls1、controls2、controls3。我想做一个作品列表sheet的名字,比如:
sheet_list <- lapply(excel_sheets('data.xlsx'), read_excel, path = 'data.xlsx')
然后,我想导入名称中包含'samples'的所有sheet,并将它们绑定到一个名为'samples'的数据框中。我怎样才能有效地完成这项工作?
你很亲近!您可以使用 lapply
等使用基础 R 来完成此操作,但我通常使用 purrr
包执行此类任务。
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)
这样做:
- 获取 sheet 的名字。
- 使用
grepl
将 sheet 子集化为仅名称中包含“samples”的那些。
- 使用
map_dfr
迭代样本sheets,读取每个样本并分配一个等于sheet名称的id列,然后将所有结果绑定在一起按行和 return 数据框。
试试这个
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)))
这是你想要的吗?
path <- "C:\your_path_here\test.xlsx"
path %>%
excel_sheets() %>%
set_names() %>%
map(read_excel, path = path)
我想从单个 .xlsx 文件导入多个 sheet,由 sheet 名称中的公共字符串选择,并将它们连接到单个数据框中。例如,如果我有一个 excel 文件 ('data.xlsx'),其中 worksheets 名为 samples1、samples2、samples3、controls1、controls2、controls3。我想做一个作品列表sheet的名字,比如:
sheet_list <- lapply(excel_sheets('data.xlsx'), read_excel, path = 'data.xlsx')
然后,我想导入名称中包含'samples'的所有sheet,并将它们绑定到一个名为'samples'的数据框中。我怎样才能有效地完成这项工作?
你很亲近!您可以使用 lapply
等使用基础 R 来完成此操作,但我通常使用 purrr
包执行此类任务。
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)
这样做:
- 获取 sheet 的名字。
- 使用
grepl
将 sheet 子集化为仅名称中包含“samples”的那些。 - 使用
map_dfr
迭代样本sheets,读取每个样本并分配一个等于sheet名称的id列,然后将所有结果绑定在一起按行和 return 数据框。
试试这个
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)))
这是你想要的吗?
path <- "C:\your_path_here\test.xlsx"
path %>%
excel_sheets() %>%
set_names() %>%
map(read_excel, path = path)