【问题标题】:R combine multiple excel sheets after applying row_to_names function over each sheetR在每张表上应用row_to_names函数后合并多个excel表
【发布时间】:2021-10-21 22:25:10
【问题描述】:

我想在 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_df 将工作表组合成单个数据框

标签: r excel dplyr openxlsx


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-06-27
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    相关资源
    最近更新 更多