首页 > 解决方案 > R在每张表上应用row_to_names函数后合并多个excel表

问题描述

我想在 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",.))

如何组合这些操作?

标签: rexceldplyropenxlsx

解决方案


您可以创建一个函数并在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)

推荐阅读