Early warning systems

Defensive R Programming

Dr. Colin Gillespie

Jumping Rivers

Early warning systems

  • Avoid problems where possible
  • Handle issues as they arise in a sensible way

As an example, using the shortcuts T/F for TRUE/FALSE

Defensive R Programming

Problem 1: TRUE and FALSE

  • TRUE and FALSE are special values
  • We can't override them
TRUE <- 5
# Error in TRUE <- 5 : invalid (do_set) left-hand side to assignment
Defensive R Programming

Problem 2: TRUE and FALSE

Suppose we are working out an F-statistic. It would be natural to have

# df is the F-density function
(F <- df(1, 9, 67))
[1] 0.7798

But R treats positive numbers as TRUE, so

if(F) message("Yer aff yer heid!")
Yer aff yer heid!

F is now treated as TRUE!

Defensive R Programming
  • Get in the habit of using TRUE and FALSE
    • not T and F
      • If you testing for TRUE, use isTRUE()
isTRUE(T)
[1] TRUE
isTRUE(2)
[1] FALSE
T <- 10
isTRUE(T)
[1] FALSE
Defensive R Programming

Let's have a little practice

Defensive R Programming

Preparing Video For Download...