首页 > 解决方案 > 如何将工作表名称作为变量添加到我的数据框中

问题描述

我有来自 excel 文件的不同工作表,我想将每个工作表导入 R 并将每个数据框中的工作表名称添加为变量,因为那时我想制作一个数据框,但我需要知道它们来自哪个工作表?

library(readxl)    
read_excel_allsheets <- function("datafile", tibble = false) {
sheets <- readxl::excel_sheets("datafile")
x <- lapply(sheets, function(X) readxl::read_excel("datafile", sheet = X))
if(!tibble) x <- lapply(x, as.data.frame)
names(x) <- sheets
x
}
#Integra las hojas en una sola
datos = x[[1]]
for(i in 2:3){
datoscompletos = rbind.data.frame(datos,x[[i]])
datos = datoscompletos
} 

标签: rexceldataframeimport

解决方案


您可以在以下位置添加一列工作表名称lapply

sheets <- readxl::excel_sheets("datafile")

all_data <- do.call(rbind, lapply(sheets, function(X) 
        transform(readxl::read_excel("datafile", sheet = X), sheetname = X)))

你可以在tidyverse

purrr::map_df(sheets, ~dplyr::mutate(readxl::read_excel("datafile", sheet = .x), 
                       sheetname = .x))

推荐阅读