Basic: RStudio
Basic: the ubiquitous x <- value
Basic: naming rules and recommendations
Basic: element type
Basic: structure type
Basic: type conversion (optional)
Basic: interact with object
Basic: read and write
Basic: subsetting
Basic: regular operations
Basic: control flow
Basic: define function
Basic: apply family
Basic: debug
Advance: data-cleaning
Advance: data-visualization
Basic: debug
写代码时,只要出现意料之外的错误(如令人心惊肉跳的
Error in xxx
,或结果与预期不符),就称之为 bug。相应的,调试或者排除错误的过程就称之为 debug。写代码的功力体现在能否写出高效、简洁且正确的代码,而要实现这个目标就必须具备扎实的 debug 能力。本节的目标就是提升 debug 的能力。
通常 bug 是非常难对付的,因为简单的错误不容易犯,而一旦有 bug,一般都比较棘手。所以,写代码就是一个不断和 bug 作斗争的过程,可以说每一个码农的成长史就是一部 debug 的“血泪史”。
Finding your bug is a process of confirming the many things that you believe are true — until you find one which is not true.
— Norm Matloff
Reference:
Debugging with the RStudio IDE
Debugging in Advanced R 2nd edition
Two types of bug: obvious one and invisible one
显性(相对简单)
所有会中止当前执行的代码并提供
Error
提示的 bug 都属于显性 bug。
隐性(相对困难)
所有不影响代码正常执行但会导致结果不对的 bug 都属于隐性 bug。例如:
要想发现隐性 bug,前提是必须对代码的执行结果有清晰的预期,否则连代码有 bug 都无法觉察,更不用提如何 debug 了。例如,上述例子中就需要用户能够清楚地知道执行结果是
1+2+3=6
,所以
b
为
5
的执行结果显然是不符合预期的,故推断出来有隐性 bug。
Three steps of debugging
通常 debug 可以包含以下三步:
在 bug 的前一行停下来
找到问题的根源
其中,2、3 步是 debug 的核心技巧,也常常一起运用。
此外,在 debug 前,
切记先把代码保存至本地
。Rstudio 的 debug 模式对于新建但未保存的代码文件(untitled)并不友好。
Step 1: Source your R script
Source (Ctrl+Shift+S):读取并执行当前活动文档中的所有代码。
相比 run current line or selection (Ctrl+Enter),Source 才是 debug 的正确姿势。因为 Run current line or selection 有 3 个缺点:
Run current line or selection 会在 console 输出执行了什么代码以及对应的结果(如果有的话),容易造成 console 信息冗杂,并且容易搞错代码执行顺序;
信息冗杂: