


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



Access any environment on the search list
as.environment('package:base')
Find the environment where a name is defined
pryr::where('func1')
There are 4 environments for functions.
Example for enclosing and binding environment y <- 1 e <- new.env() e$g <- function(x) x + y
environment, and the binding environment is āeā.
Figure 2. Function Environment
Note: Every R package has two environments associated with it (package and namespace). Every exported function is bound into the package environment, but enclosed by the namespace environment.
Note: Each execution environment has two parents: a calling environment and an enclosing environment.
Assignment
Name rules
Regular assignment arrow, <-
What is the Search Path? An R internal mechansim to look up objects, specifically, functions.
Figure 1. The Search Path
If there are functions with the same name in two different packages, the latest package will get called.
search() : '.GlobalEnv' ... 'Autoloads' 'package:base' library(reshape2); search() '.GlobalEnv' 'package:reshape2' ... 'Autoloads' 'package:base'
Note: There is a special environment called Autoloads which is used to save memory by only loading package objects (like big datasets) when needed.
What is an Environment?
Data structure (that powers lexical scoping) is made up of two components, the frame, which contains the name- object bindings (and behaves much like a named list), and the parent environment.
Named List
Parent Environment
Environments can also be useful data structures in their own right because they have reference semantics.
The parent of the global environment is the last package that you attached with library() or require().
data structures
Functions
Homogeneous Heterogeneous
1d Atomic vector List
2d Matrix Data frame
nd Array
Note: R has no 0-dimensional or scalar types. Individual numbers or strings, are actually vectors of length one, NOT scalars.
Human readable description of any R data structure:
str(variable)
Every Object has a mode and a class
The most important thing to understand about R is that functions are objects in their own right.
All R functions have three parts:
body() code inside the function
formals() list of arguments which controls how you can call the function
environment() āmapā of the location of the functionās variables (see āEnclosing Environmentā)
Every operation is a function call
Note: the backtick (), lets you refer to functions or variables that have otherwise reserved or illegal names: e.g. x + y is the same as+`(x, y)
What is Lexical Scoping?
Looks up value of a symbol. (See "Enclosing Environment" in the "Environment" section.)
f <- function() x + 1 codetools::findGlobals(f) > '+' 'x'
environment(f) <- emptyenv() f()
***** (^) This doesnāt work because R relies on lexical scoping to find everything, even the + operator. Itās never possible to make a function completely self-contained because you must always rely on functions defined in base R or other packages.
When calling a function you can specify arguments by position, by complete name, or by partial name. Arguments are matched first by exact name (perfect matching), then by prefix matching, and finally by position.
%+% <- function(a, b) paste0(a, b) 'new' %+% 'string'
%||% <- function(a, b) if (!is. null(a)) a else b function_that_might_return_null() %||% default value
second<- <- function(x, value) { x[2] <- value x } x <- 1: second(x) <- 5L
typeof() class()
strings or vector of strings character character
numbers or vector of numbers numeric numeric
list list list
data.frame* list data.frame
Type typeof() what it is
Length length() how many elements
Attributes attributes() additonal arbitrary metadata
levels(x) # defines the set of allowed values
Names a character vector giving each element a name names(x)
Dimensions used to turn vectors into matrices and arrays dim(x)
Class used to implement the S object system class(x)
data structures
i <- function(a, b) { missing(a) -> # return true or false }
f <- function(x) { 10 } f(stop('This is an error!')) -> 10
However, since x is not used. stop("This is an error!") never get evaluated.
f <- function(x = ls()) { a <- 1 x }
f() -> 'a' 'x' ls() evaluated inside f
f(ls()) ls() evaluated in global environment
sum : function (..., na.rm = FALSE) .Primitive('sum')
debugging, condition handling , & deFensive programming object oriented (oo) Field guide
Created by Arianne Colton and Sean Chen [email protected] Based on content from āAdvanced Rā by Hadley Wickham Updated: January 15, 2016
Use traceback() and browser(), and interactive tools in RStudio:
This is useful because often the root cause of the error is a number of calls back.
Then, in a later interactive R session, you load that file, and use debugger() to enter an interactive debugger with the same interface as recover(). This allows interactive debugging of batch code.
In batch R process ----
dump_and_quit <- function() {
dump.frames(to.file = TRUE)
q(status = 1) } options(error = dump_and_quit)
In a later interactive session ----
load("last.dump.rda") debugger()
For example, the Date method for the mean() generic is called mean.Date()
This is the reason that most modern style guides discourage the use of. in function names, it makes them look like S3 methods.
methods('mean')
#> mean.Date #> mean.default #> mean.difftime
methods(class = 'Date')
Check if an object is a S3 object
is.object(x) & !isS4(x) or pryr::otype()
Check if inherits from a specific class inherits(x, 'classname')
Determine class of any object class(x)
R has three object oriented systems (plus the base types)
Example: drawRect(canvas, 'blue')
Langauge: R
Example: canvas.drawRect('blue')
Langauge: Java, C++, and C#
typeof() # determines an object's base type
that can easily be suppressed by the user using ?suppressMessages().
result = tryCatch(code, error = function(c) "error", warning = function(c) "warning", message = function(c) "message" )
Use conditionMessage(c) or c$message to extract the message associated with the original error.
If successful, it will be the last result evaluated in the block, just like a function. If unsuccessful it will be an invisible object of class "try-error".
The basic principle of defensive programming is to " fail fast ", to raise an error as soon as something goes wrong.
In R, this takes three particular forms:
These functions save time when used interactively, but because they make assumptions to reduce typing, when they fail, they often fail with uninformative error messages.
Note: Whenever subsetting a data frame in a function, you should always use drop = FALSE