前一段,写过一篇:R语言中写入Excel的不同sheet表格,最近学习了tidyverse的方法,感觉需要总结一下,更新一下知识结构。 本文准备用实际数据,做一下操作: 「批量读取:」 「批量写入」 1. 模拟数据模拟数据的过程很简单,新建一个Excel,里面加点内容,然后复制粘贴,重命名。 ❝懂了这么多编程知识,这一步显得不够高科技,但是确实是很直接。 ❞  
2. 批量读取2.1 批量读取多个Excel数据「步骤:」 library(tidyverse) library(openxlsx)
list_name = dir("./",pattern = ".xlsx") list_name
re = map(list_name, ~ read.xlsx(.,sheet=1)) re names(re) = list_name re write.xlsx(re,"../re_hebing.xlsx")
目录: 读取结果: 结果文件: 在这里插入图片描述 2.2 批量读取一个Excel的不同sheet表格「步骤:」 name_sheet = 1:8 re2 = map(name_sheet, ~ read.xlsx("../re_hebing.xlsx",sheet=.)) re2
 3. 批量写入3.1 批量写入到不同的Excel中「步骤:」 - 内容为list,每个元素为一个data.frame
这里,我们用re 的结果: > str(re) List of 8 $ a1.xlsx:'data.frame':4 obs. of 2 variables: ..$ ID: num [1:4] 1 2 3 4 ..$ y : num [1:4] 0.6275 0.4325 0.6046 0.0681 $ a2.xlsx:'data.frame':4 obs. of 2 variables: ..$ ID: num [1:4] 1 2 3 4 ..$ y : num [1:4] 0.6275 0.4325 0.6046 0.0681 $ a3.xlsx:'data.frame':4 obs. of 2 variables: ..$ ID: num [1:4] 1 2 3 4 ..$ y : num [1:4] 0.6275 0.4325 0.6046 0.0681 $ a4.xlsx:'data.frame':4 obs. of 2 variables: ..$ ID: num [1:4] 1 2 3 4 ..$ y : num [1:4] 0.6275 0.4325 0.6046 0.0681 $ a5.xlsx:'data.frame':4 obs. of 2 variables: ..$ ID: num [1:4] 1 2 3 4 ..$ y : num [1:4] 0.6275 0.4325 0.6046 0.0681 $ a6.xlsx:'data.frame':4 obs. of 2 variables: ..$ ID: num [1:4] 1 2 3 4 ..$ y : num [1:4] 0.6275 0.4325 0.6046 0.0681 $ a7.xlsx:'data.frame':4 obs. of 2 variables: ..$ ID: num [1:4] 1 2 3 4 ..$ y : num [1:4] 0.6275 0.4325 0.6046 0.0681 $ a8.xlsx:'data.frame':4 obs. of 2 variables: ..$ ID: num [1:4] 1 2 3 4 ..$ y : num [1:4] 0.6275 0.4325 0.6046 0.0681
这里,我们将工作目录设置为上一级,用map2 进行操作: setwd("../") sheet_name = names(re) sheet_name map2(re,sheet_name,write.xlsx)
结果: 3.2 批量写入到同一个Excel中不同sheet表格这就不用操作,直接写入就行了,一行代码: write.xlsx(re,"new_new_many_sheets.xlsx")
 
4. 知识点总结- 写入多个Excel时,用了map2函数,其实还可以用walk2函数,walk2就不会返回结果到终端了
- 默认的write.xlsx函数,支持写入list就是多个sheet表格
- 有时候重命名list更有用,比如写入到不同sheet表格中,名称就是不同sheet表的名称
- 读取不同sheet表格时,可以用1,2,3表示对应的sheet
- 另外,如果想把批量读取的Excel进行行合并或者列合并,可以用map_dfc或者map_dfr更简单。当然,后面也可以用map再做处理
|