library(readxl)library(tidyverse)library(writexl)
第 20 章 电子表格 电子表格
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
导言
在第 7 章中,你学习了从.csv 和.tsv 等纯文本文件导入数据。现在该学习如何从电子表格(Excel 电子表格或 Google Sheet)中获取数据了。本章将以第 7 章所学的大部分内容为基础,但我们还将讨论在处理电子表格数据时的其他注意事项和复杂性。
如果您或您的合作者正在使用电子表格组织数据,我们强烈建议您阅读 Karl Broman 和 Kara Woo 撰写的论文《电子表格中的数据组织》。当您从电子表格中导入数据到 R 中进行分析和可视化时,这篇论文中介绍的最佳实践将为您省去很多麻烦。
在 Excel
Microsoft Excel 是一种广泛使用的电子表格软件程序,数据被组织在电子表格文件内的工作表中。
先决条件
在本节中,您将学习如何使用 readxl 软件包在 R 中加载 Excel 电子表格中的数据。该软件包属于非核心的 tidyverse,因此需要显式加载,但在安装 tidyverse 软件包时会自动安装。稍后,我们还将使用 writexl 软件包,它允许我们创建 Excel 电子表格。
入门
readxl 的大多数函数都允许您将 Excel 电子表格加载到 R 中:
-
read_xls()读取XLS格式的 Excel 文件。 -
read_xlsx()读取XLSX格式的 Excel 文件。 -
read_excel()可以读取XLS和XLSX两种格式的文件。它会根据输入内容猜测文件类型。
这些函数的语法与我们之前介绍的用于读取其他类型文件的函数类似,例如 read_csv(), read_table()等。在本章接下来的内容中,我们将重点使用 read_excel().
阅读 Excel 电子表格
图 20-1显示了我们要读入 R 的电子表格在 Excel 中的样子。
图 20-1. Excel 中名为students.xlsx 的电子表格。
的第一个参数 read_excel()的第一个参数是要读取文件的路径。
students<-read_excel("data/students.xlsx")
read_excel()将以 tibble 形式读入文件。
students#> # A tibble: 6 × 5#> `Student ID` `Full Name` favourite.food mealPlan AGE#> <dbl> <chr> <chr> <chr> <chr>#> 1 1 Sunil Huffmann Strawberry yoghurt Lunch only 4#> 2 2 Barclay Lynn French fries Lunch only 5#> 3 3 Jayendra Lyne N/A Breakfast and lunch 7#> 4 4 Leon Rossini Anchovies Lunch only <NA>#> 5 5 Chidiegwu Dunkel Pizza ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access