Chapter 6 Loop functions
lapply sapply tapply mapply apply: let’s set margins
gl
6.1 Debbuging and error handling
- message: informative
- warnings: unexpected behavior, display once execution has finished
- error: fatal breaks the program
- condition: generic
out printing to the console
useful tools
traceback debug browser trace recover
blunt techniques insert cat/ print staments insid the function
mean(x)
traceback()
debug(lm)
lm(x-y)
undebug(lm)
optins(error=recover)
optins(error=browser)
optins(error=NULL)
<<- is an operator used to assign a object to a different environment
6.2 R objects
6.3 Create package documentation
Run devtools::document()
(or press Ctrl/Cmd + Shift + D in RStudio) to convert roxygen comments to .Rd files.
6.4 SWIRL practices
6.4.1 lapply sapply
loop functions or *apply functions
split apply combine strategy lay out by Hadley Wickham in his paper titled ‘The Split-Apply-Combine Strategy for Data Analysis’.
Rows observation and columns variables
specify its own anonymous function lapply(unique_vals, function(elem) elem[2])
back in week to we read some data from a file. Imagine we want to analyze this information we want to know what type is. first we try simply to find the class of students which ain’t very us
Now we want to iterate operation over it lapply returns a list type as a result. sapply tries to simplify whenever is possible. iF every result is of length 1 it returns a vector if they are all bigger than one and with the same length it returns a matrix.
## [1] "data.frame"
6.4.2 vapply and tapply
vapply allows to specify the format of the result and throughs an error if not matched.
more in depth of the source function source from web github
## [1] " I am filed called from a URL"
## [1] "In R, the source function allows to call either files path names or URL connettion"
One can call an R script and all its content using source. R can also interface with different files compress files using … and web pages using the url function.
#remove(list=ls())
#source("code/simple_script.R", encoding = 'UTF-8')
#eval(parse("simple_script.R", encoding="UTF-8"))
#roll()
#dput(rank)
#dump(c(rank,rolls))
## [1] "Name and Lastname; ID; email adress"
## [2] "Samuel Jackson; 10124585611; samuelJ@mail.com"
## [3] "Robert Downey; 4525111559; rdownironman@mail.c"
## [4] "Douglas Adams; 14884674721; zaphodbeeblebrox@mail.com"
## [5] "Stephen Wolfram; 74682868914; wolframalpha@mail.com"
r measure run time and optimization