Skip to Content
高效R语言编程
book

高效R语言编程

by Colin Gillespie, Robin Lovelace
August 2018
Intermediate to advanced
227 pages
4h 16m
Chinese
China Electric Power Press Ltd.
Content preview from 高效R语言编程
高效编程
65
通常,类别变量存成
1
2
3
4
5
的形式,并另附文档说明各数字的含义。
明显这很痛苦。当然,我们可将数据存成字符向量。尽管这样看起来很好,
但语法上是错误的,因为没有表达出这是一个类别变量。既然因子有正反两面,
那么总用或者永远不用因子都是不明智的。实际上,我们需要具体情况具体
分析。
通常来说,如果你的变量有固有排序(例如从大到少)或者你有固定不变的
类别集合,你该考虑使用因子。
内在排序
因子可用于图形排序。例如假设我们有一个数据集,其中 type变量有三个
可能取值:smallmediumlarge。显然,这是有序的。使用一个标准的
boxplot() 函数调用:
boxplot(y ~ type)
将创建箱线图(
boxplot
,
其中
x
轴是按照字符排序的。将变量 type 转换成因子,
我们很轻松地定义了正确的排序。
boxplot(y ~ factor(type, levels = c("Small", "Medium", "Large")))
多数用户使用 read.csv() 函数与因子打交道,该函数将字符列自动转
换成因子。如果数据混乱并且我们要清理重编数据,该函数的自动转
换功能是很讨厌的。通常在使用 read.csv() 读取数据时,我们将参数
stringsAsFactors
设置为 FALSE。尽管可将该参数添加到全局 options()
列表并放入
.Rprofile
文件中,但这容易导致不可移植代码,通常避免这样做。
固定类别
假如我们的数据集是月份相关的
m =
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

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

数据科学之编程技术:使用R进行数据清理、分析与可视化

数据科学之编程技术:使用R进行数据清理、分析与可视化

迈克尔 弗里曼, 乔尔 罗斯
R数据科学

R数据科学

Hadley Wickham, Garrett Grolemund

Publisher Resources

ISBN: 9787519820855