Myfunc takes two arguments, v1 and v2, and returns the larger of the two. v2 has a default value of 5, so if it is not supplied, the function will compare v1 to 5.
myfunc <-function(v1, v2 =5) {max(v1, v2)}
myfunc(1,2)
[1] 2
myfunc(1,2,3)
Error in `myfunc()`:
! unused argument (3)
myfunc(c(1,2))
[1] 5
The last call returns 5 and not 2 because the whole c(1,2) is supplied for v1 and no object is supplied for v2.
Scoping: functions use “local” names
x <-10show_local <-function() { x <-20 x}c(show_local(), x)
[1] 20 10
Function call creates local names
Local assignment stays local
Outer name unchanged
Where does R look for a name?
x <-10add_outer_x <-function(z) { z + x}add_outer_x(5)
[1] 15
Function arguments and local names first
Then surrounding names
If still missing: object 'name' not found
Convenient but bug prone
Pass all used objects as arguments
You need to tell R where to look
toy_df <-data.frame(x =c(1, 2, 3),y =c(2, 4, 5))
lm(y ~ x)
Error:
! object 'y' not found
coef(lm(y ~ x, data = toy_df))
(Intercept) x
0.6666667 1.5000000
x and y are column names inside toy_df
lm(y ~ x) looks for objects named x and y
data = toy_df tells R where to look
Packages, Comments, Errors, and Help
Expressions, Operators, And Assignment
Objects And Types
Logic And Missingness
Control Flow
Functions
Packages, Comments, Errors, and Help
Packages extend R
Packages add functions, datasets, and tools:
install.packages("ggplot2")library(ggplot2)
Install once
Load when needed
Read package documentation
package::function() syntax
This pattern makes the source of a function explicit:
Comments start with
#Comments are text for humans. The interpreter ignores them:
But: “Good code explains itself”