May 2025
Intermediate to advanced
578 pages
8h 9m
Chinese
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
使用 R 软件包提供的数据是学习数据科学工具的好方法,但你也希望能将所学应用到自己的数据中。在本章中,你将学习将数据文件读入 R 的基础知识。
具体来说,本章将重点介绍如何读取纯文本矩形文档。我们将从处理列名、类型和缺失数据等特征的实用建议开始。然后,您将学习如何一次性从多个文件中读取数据,以及如何将数据从 R 写入文件。最后,您将学习如何在 R 中手工制作数据帧。
在本章中,你将学习如何使用作为核心 tidyverse 一部分的 readr 软件包在 R 中加载平面文件:
library(tidyverse)
开始,我们将重点介绍最常见的矩形数据文件类型:CSV 是 "逗号分隔值 "的简称。下面是一个简单的 CSV 文件。第一行通常称为标题行,给出列名,下面六行提供数据。各列之间用逗号隔开,又称分隔。
Student ID,Full Name,favourite.food,mealPlan,AGE
1,Sunil Huffmann,Strawberry yoghurt,Lunch only,4
2,Barclay Lynn,French fries,Lunch only,5
3,Jayendra Lyne,N/A,Breakfast and lunch,7
4,Leon Rossini,Anchovies,Lunch only,
5,Chidiegwu Dunkel,Pizza,Breakfast and lunch,five
6,Güvenç Attila,Ice cream,Lunch only,6
表 7-1表示与表格相同的数据。
| 学生证 | 全名 | favourite.food | 用餐计划 | 年龄 |
|---|---|---|---|---|
| 1 | 苏尼尔-哈夫曼 | 草莓酸奶 | 仅限午餐 | 4 |
| 2 | 巴克利-林恩 | 炸薯条 | 仅限午餐 | 5 |
| 3 | Jayendra Lyne | 不适用 | 早餐和午餐 | 7 |
| 4 | 莱昂-罗西尼 | 鳀鱼 | 仅限午餐 | NA |
| 5 | 奇迪格乌-邓克尔 | 比萨 | 早餐和午餐 | 五个 |
| 6 | 居文奇-阿提拉 | 冰淇淋 | 仅限午餐 | 6 |
我们可以使用 read_csv().第一个参数是最重要的:文件路径。你可以把路径看作文件的地址:文件名是students.csv ,它位于data 文件夹中。
students<-read_csv("data/students.csv")#> Rows: 6 Columns: 5#> ── Column specification ─────────────────────────────────────────────────────#> Delimiter: ","#> chr (4): Full Name, favourite.food, mealPlan, AGE#> dbl (1): Student ID#>#> ℹ Use `spec()` to retrieve the full column specification for this data.#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message. ...
Read now
Unlock full access