育种数据分析之放飞自我分享 http://blog.sciencenet.cn/u/yijiaobai 关注:生物统计,数量遗传,混合线性模型,生物信息,R,Perl,Python,GWAS,GS相关方法,文章及代码

博文

总结 | R语言批量读取写入Excel数据

已有 5654 次阅读 2021-6-19 17:21 |个人分类:农学统计|系统分类:科研笔记


前一段,写过一篇:R语言中写入Excel的不同sheet表格,最近学习了tidyverse的方法,感觉需要总结一下,更新一下知识结构。

本文准备用实际数据,做一下操作:

「批量读取:」

  • 批量读取多个Excel数据
  • 批量读取一个Excel数据的不同表格

「批量写入」

  • 批量写入Excel数据
    • 1,批量写入到不同的Excel中
    • 2,批量写入到一个Excel的不同表格中

1. 模拟数据

模拟数据的过程很简单,新建一个Excel,里面加点内容,然后复制粘贴,重命名。

懂了这么多编程知识,这一步显得不够高科技,但是确实是很直接。

2. 批量读取

2.1 批量读取多个Excel数据

「步骤:」

  • 先把目录下的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表格

「步骤:」

  • 共有8个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. 知识点总结

  • 使用了map和匿名函数进行批量操作
  • 写入多个Excel时,用了map2函数,其实还可以用walk2函数,walk2就不会返回结果到终端了
  • 默认的write.xlsx函数,支持写入list就是多个sheet表格
  • 有时候重命名list更有用,比如写入到不同sheet表格中,名称就是不同sheet表的名称
  • 读取不同sheet表格时,可以用1,2,3表示对应的sheet
  • 另外,如果想把批量读取的Excel进行行合并或者列合并,可以用map_dfc或者map_dfr更简单。当然,后面也可以用map再做处理
  • 总之,map函数就是批量操作的,越用越6




> 欢迎关注我的公众号:`育种数据分析之放飞自我`。主要分享R语言,Python,育种数据分析,生物统计,数量遗传学,混合线性模型,GWAS和GS相关的知识。




https://wap.sciencenet.cn/blog-2577109-1291841.html

上一篇:一文讲清遗传相关
下一篇:数量遗传学,分享几本书的电子版
收藏 IP: 223.90.189.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-19 04:07

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部