r - 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",.))
如何组合这些操作?
解决方案
您可以创建一个函数并在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)
推荐阅读
- angular - UI 未在 IE 中更新,Array 正在使用 ngFor 显示
- angular - Moment() 未在 Angular 中定义
- highcharts - Highcharts 区域填充顶部
- java - Cmake 在构建 OpenCv 时无法识别 java
- hibernate - 如何在hibernate中编写SQL sum() 和groupby?
- sql - 仅当值不同时,才在不同实例上从模式 A 更新到模式 B
- vba - 在输入数组之前从变量帖子中减去值
- html - 当尺寸缩小到移动设备时图片消失
- .net-core - .NET Core 2.0 LDAP/AD 身份验证使用 SSL VPN 隧道
- delphi - Delphi:.dcu 未找到,但代码可在另一台计算机上运行