r - 如何将工作表名称作为变量添加到我的数据框中
问题描述
我有来自 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
}
解决方案
您可以在以下位置添加一列工作表名称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))
推荐阅读
- python - 导入的模块不导入
- angular - Angular2将平面json加载为嵌套反应形式(结构不一样)
- prometheus - Prometheus - 为平均订单大小、订单处理时间和订单之间的时间设计自定义指标
- python - 具有 StratifiedKFold 的 CatboostRegressor 的值错误
- oauth - 将 OIDC IDP 插入现有的 SP SAML 连接
- cygwin - 如何在命令行中从 Cygwin 安装软件包?
- oracle - 批量将数据从 Source 加载到 Salesforce
- c# - 如何在 C# 中反序列化 ksql 查询的行键?
- sql - Ms Access SQL 如何消除重复值
- python - Django / HTML提交按钮重定向到错误页面