首页 > 解决方案 > 比较excel文件中多张工作表的列标题并将其提取到R

问题描述

所以我有一个 excel 文件,其中包含我必须合并的几张表中的数据,以便我可以从中提供见解:

这些表以从 11 月开始的每个月命名...... 10 月(共:12 张)

我的代码开始是这样的:

#List of months to look at
months = c("Novemeber", "December", "January", "February", "March", "April", "May", "June", "July", "August", "September")

我想要做的是将这些工作表中的每一个的列名与一个空的 df 匹配(我称之为差异)并相应地将数据获取到这些列。我的代码是这样的

discrepancies <-
  setNames(
    data.frame(matrix(ncol = 12, nrow = 0)),
    c(
      "Date",
      "Officer",
      "Case Number",
      "Account Number",
      "Plan Type",
      "Type",
      "ID",
      "Transaction Amount",
      "Code",
      "Specialist",
      "Transit#",
      "Processed Via"
      )
  )
#Query for each month's data and append to the main dataframe
for (i in months) {
  temp <- read_excel(
    "G:/Confidental.xlsx",
    sheet = i,
    col_names = TRUE,
    skip = 0
  )
  temp$`months` <- i
  discrepancies <- rbind(discrepancies, temp)
}

此代码将工作表中的每个字段与我想要的列进行比较,当一张表的列数与差异 df 中的列数不同时,它会卡住。任何帮助表示赞赏。

标签: r

解决方案


我认为您不需要创建一个空数据框来比较所有列。试试这种方法:

library(readxl)
result <- purrr::map_df(months, ~read_excel("G:/Confidental.xlsx",sheet = .x), 
                       .id = 'months')

这将结合在一个数据框上的所有工作表中。如果工作表中不存在某些列,则会自动插入该NA月的这些列。


推荐阅读