EduCAT: R

Notes from Advanced R by Hadley Wickham

Data Structures


Vectors

Attributes

Factors

Matrices and Arrays

Data frames



Subsetting


Data types

Subsetting Operators

Applications



Vocabulary


Basics

match assign get all.equal complete.cases cummax, cummin rle missing on.exit invisible setdiff setequal which sweep data.matrix rep_len seq_len, seq_along split expand.grid next, break switch sapply, vapply apply tapply replicate

Common Data Structure Vocab

Working with R

ls, exists library, require # What's the difference? demo example # Debugging traceback browser recover options(error = ) stop, warning, message tryCatch, try

I/O



Style


Tips



Functions


Components

  • Name masking - names of objects belong to their environment
  • Functions vs Variables
  • Fresh start - exists() function
  • Dynamic lookup
    • codetools::findGlobals() - gives a function's external dependencies
    • You must always rely on functions defined in base R or other R packages.
    • Note you could turn ( into a function!

    Every Operation is a Function Call

    • "Everything that exists is an object; everything that happens is a function call." John Chambers (Creator of the S programming language)
    • Equivalent operations (note backticks, not apostrophes) x + y `+` (x, y)
    • sapply() - powerful function accepts "+" and `x`

    Function Arguments

    • Call a function - specify arguments by complete or partial names f <- function(catalog, peril, region){ list(c = catalog, p = peril, r=region) }
    • To publish code on CRAN you must use complete names.
    • Send a list to a function using do.call() do.call(mean, args)
    • Setting default values

    Special Calls

    • Prefix arguments: names of functions come before e.g. mean()
    • Infix arguments: names in-between e.g. +, -, >
    • Replacement functions

    Return Values

    • Suggests reserving explicit return(y) for early returns.
    • See also invisible() values.
    • The function on.exit() restores any changes to global state by impure functions.
    • Hadley's example: in_dir <- function(dir, code) { old <- setwd(dir) on.exit(setwd(old)) force(code) } getwd()


    OO Field Guide



    Alastair Clarke
    11th December, 2018