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语言编程
62
3
是否丢失参数或数值计算失败?有三种主要的与用户交互的技巧。
致命错误
: stop()
调用 stop() 抛出致命错误(例如,执行被终止)。一个函数调用 stop() 后,
将不再执行任何其他操作。当我们使用 rnorm() 成随机数时,第一个参数
n 是样本数。如果要返回的观测数小于
1
,将产生错误。当我们要抛出错误时,
尽快抛出,否则就是在浪费资源。因此,一个函数的前几行代码通常进行参
数检查。假设我们调用了一个函数并引发了错误,后续该如何做?高效、健
壮的代码捕获错误并做出相应处理。使用 try() tryCatch() 捕获错误。例如:
#
抑制错误信息
good = try(1 + 1, silent = TRUE)
bad = try(1 +
1
, silent = TRUE)
当我们查看对象时,变量 good 仅包含数值 2
good
#> [1] 2
然而,bad 对象是一个包含错误信息的字符串,属于 try-error 类,具有
condition
属性。
bad
#> [1] "Error in 1 + \"1\" : non-numeric argument to binary operator\n"
#> attr
,"class"
#> [1] "try-error"
#> attr
,"condition"
#> <simpleError in 1 + "1": non-numeric argument to binary operator>
我们可以在标准条件表达式中使用该信息: ...
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