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语言编程
高效优化
143
高效的基础
R
R
中,解决问题的方法通常不止一种,本节中我们特意给出可改善性能的标
准方式或替代方法。
if()
函数与
ifelse()
函数
ifelse() 是标准控制流程函数 iftest if_yes else if_no 向量化版本,
执行方式如下:
ifelse(test, if_yes, if_no)
在上面的虚构例子中,如果 test 的值为 TRUE 或者 FALSE
,
则返回值是 if_yes
if_no。例如,假如我们有一成绩表向量,ifelse() 可用于区分通过或未
通过:
marks = c(25, 55, 75)
ifelse(marks >= 40, "pass", "fail")
#> [1] "fail" "pass" "pass"
如果判断 (test) 条件的长度是
1
(例 lengthtest == 1
,
则标准条件
判断语句:
mark = 25
if
mark >= 40
{
"pass"
} else {
"fail"
}
比下面的语句快大约
5
10
ifelse(mark >= 40, "pass", "fail")
ifelse() 另外的特异之处是:尽管它属于程序员级高效,因为它清晰明了、
比多行代码形式简洁易懂;但它往往比一个冗长的代码的计算效率更低。下
面代码基准测试结果说明这点:尽管两种计算结果一样,不过第二种形式速
度快大约
20
倍。
marks = runif(n = 10e6, min = 30, max = 99)
system.time ...
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