R在每张表上应用row_to_names函数后合并多个excel表

标签 r excel dplyr openxlsx

我想在 r 中合并来自 excel 文件的多张工作表,并且对于每张工作表,在合并之前,应用操作 a(每个工作表在标题行上方的单元格 a1 中都有一个唯一的 id 名称 - 操作 a 将其删除,并创建一个新的 id 列使用该值(感谢@akrun))。为每张纸完成此操作后,我想使用操作b进行组合:

#operation a
#this works for one sheet, removes value in cell a1 and uses as value in new id column

library(openxlsx)
library(dplyr)
library(tidyr)

df1 <- read.xlsx("mydata.xlsx") 
df1 %>%
   row_to_names(1) %>%
   mutate(id = colnames(df1)[1])
#operation b
#this combines all the sheets but I would like operation a to be applied to each sheet first
library(tidyverse)
library(readxl)

combined <- excel_sheets("mydata.xlsx") %>% 
  map_df(~read_xlsx("mydata.xlsx",.))
如何组合这些操作?

最佳答案

您可以创建一个函数并在 map 中使用它.

library(dplyr)
library(janitor)
library(readxl)

change_column_names <- function(df1) {
  df1 %>%
    row_to_names(1) %>%
    mutate(id = colnames(df1)[1])
}

excel_sheets("mydata.xlsx") %>%
  purrr::map_df(~read_xlsx("mydata.xlsx", .x) %>% change_column_names)

关于R在每张表上应用row_to_names函数后合并多个excel表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68860922/

相关文章:

带有离散色标的光栅图,用于负值和正值 R

r - 根据 OID 按类别拆分数据帧

r - 当我尝试在 dplyr group_map 函数中使用 defuse-inject 模式时失败

r - 在 R 中使用多个条件对分类数据进行子集化的快速方法

r - 使用 knitr 制作动画 rgl 图表

关于两个向量的差、交和并

r - 使用unique()和==来匹配带重音和不带重音的字符

java - 使用 Apache POI 在条件格式中自定义背景颜色

php - 将数组从 vba 传递到 php Web 服务

excel - 使用公式将 10 进制转换为 36 进制