r - 比较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 中的列数不同时,它会卡住。任何帮助表示赞赏。
解决方案
我认为您不需要创建一个空数据框来比较所有列。试试这种方法:
library(readxl)
result <- purrr::map_df(months, ~read_excel("G:/Confidental.xlsx",sheet = .x),
.id = 'months')
这将结合在一个数据框上的所有工作表中。如果工作表中不存在某些列,则会自动插入该NA
月的这些列。
推荐阅读
- swift - 如何将经度和纬度变量传递给另一个函数?
- firebase - Firebase 规则设置
- ruby-on-rails - 如何检查是否使用 RSpec 调用了内部方法
- javascript - Snake Code - 使蛇的脸成为图像
- mysql - 需要帮助将 SQL 查询转换为 JPQL
- javascript - react中的数据存储在哪里?
- arrays - VBA_Excel_For 循环 1 值太多
- azure - Azure 应用服务错误:请求中指定的回复 URL 与为应用程序配置的回复 URL 不匹配
- selenium - Selenium, Too many "divs" to select Cant select....(初学者)(我放弃)
- r - 如何在ggplot中显示不同条件下二元结果的变化比例?