EduCAT: Advanced R
Notes from Advanced R by Hadley Wickham
Debugging
Technique
- Take the scientific approach:
- Develop a hypothesis
- Perform experiments to test that hypothesis
- Relate findings to the original hypothesis
- Instead of writing one big function that does everything, create smaller functions that work together (or sequentially).
Tools
-
traceback()
shows you where the error occurred. Read its output from bottom-to-top. - RStudios' 'Rerun with Debug' tool reruns the codes and pauses where the error occurred.
Condition Handling
- Use case: fitting many models to data and one model fails.
- Three tools:
try(), tryCatch()
andwithCallingHandlers()
. - Create a built-in function to test for the try-error class and easily identify inputs that failed.
Defensive Programming
- Use
stopifnot()
say if your function requires a data.table as an input.
Functional Programming
Motivation
- Functions can be assigned to variables, stored in lists, passed as arguments to other functions, create inside other functions, and return them as the result of another function.
- Do Not Repeat Yourself - every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
- Combining a function with the
lapply()
functional. - Closures make and return functions.
Anonymous Functions and Closures
- Functions without a name. Useful with
integrate()
orlapply()
. - Mutable states e.g. variables holding different values at different levels or states, such as the iteration counter.
- Functionals are useful when you have several functions that are variations on a theme e.g. AEP or OEP, Ground-up or Gross.
- Pythagorean means: Arithmetic, Geometric and Harmonic
pymean <- function(kind){ if (kind=="a"){ function(x) sum(x)/length(x) } else if (kind=="g") { function(x) (prod(x))^(1/length(x)) } else if (kind=="h") { function(x) length(x)/sum(1/x) } } $ pymean("h")(c(1,4,4)) $ 2
Alastair Clarke
27th April, 2019