Activity
Work on the warmup activity (handout), then we will discuss as a class
Ordering and arguments
my_power <- function(x, y){
return(x^y)
}
- If you don’t name the arguments when calling a function, R assumes you passed them in the order of the function definition
Function defaults
my_power <- function(x, y){
return(x^y)
}
What will happen when I run the following code?
Function defaults
my_power <- function(x, y){
return(x^y)
}
What will happen when I run the following code?
Error in my_power(3): argument "y" is missing, with no default
Function defaults
my_power <- function(x, y=2){
return(x^y)
}
What will happen when I run the following code?
Function defaults
my_power <- function(x, y=2){
return(x^y)
}
What will happen when I run the following code?
Function defaults
my_power <- function(x, y=2){
return(x^y)
}
What will happen when I run the following code?
Function defaults
my_power <- function(x, y=2){
return(x^y)
}
What will happen when I run the following code?
Function defaults
my_power <- function(x, y){
return(x^y)
}
What will happen when I run the following code?
Function defaults
my_power <- function(x, y){
return(x^y)
}
What will happen when I run the following code?
Error in my_power(3): argument "y" is missing, with no default
Function defaults
my_power <- function(x=2, y=4){
return(x^y)
}
What will happen when I run the following code?
Function defaults
my_power <- function(x=2, y=4){
return(x^y)
}
What will happen when I run the following code?
Function scoping
What value will the following code return?
g01 <- function(x = 10) {
return(x)
}
g01()
Function scoping
What value will the following code return?
g01 <- function(x = 10) {
return(x)
}
g01()
What if I try to look at x?
Function scoping
What value will the following code return?
g01 <- function(x = 10) {
return(x)
}
g01()
What if I try to look at x?
Error: object 'x' not found
- Variables created within functions don’t exist outside the function!
Function scoping
Variables created within functions don’t exist outside the function!
g01 <- function() {
x <- 10
return(x)
}
g01()
Error: object 'x' not found
Function scoping
What will the following code return?
x <- 10
g01 <- function(){
return(x)
}
g01()
Function scoping
x <- 10
g01 <- function(){
return(x)
}
g01()
- If a variable is not defined in a function, R looks outside the function (the global environment)
Name masking
What value will the following code return?
x <- 10
g01 <- function() {
x <- 20
return(x)
}
g01()
x
Name masking
What value will the following code return?
x <- 10
g01 <- function() {
x <- 20
return(x)
}
g01()
- Names defined inside a function mask names defined outside a function
- Variables created within a function don’t exist outside
Summary
- Variables created within a function don’t exist outside
- If a variable is not defined in a function, R looks outside the function
- Names defined inside a function mask names defined outside a function