Scope and precedence

Introduction to Writing Functions in R

Richie Cotton

Data Evangelist at DataCamp

Accessing variables outside functions

x_times_y <- function(x) {
  x * y
}
x_times_y(10)
Error in x_times_y(10) : 
  object 'y' not found
x_times_y <- function(x) {
  x * y
}
y <- 4
x_times_y(10)
40
Introduction to Writing Functions in R

Accessing function variables from outside

x_times_y <- function(x) {
  x * y
}
y <- 4
x_times_y(10)
print(x)
Error in print(x) : object 'x' not found
Introduction to Writing Functions in R

What's best? Inside or outside?

x_times_y <- function(x) {
  y <- 6
  x * y
}
y <- 4
x_times_y(10)
60
Introduction to Writing Functions in R

Passed in vs. defined in

x_times_y <- function(x) {
  x <- 9
  y <- 6
  x * y
}
y <- 4
x_times_y(10)
54
Introduction to Writing Functions in R

Let's practice!

Introduction to Writing Functions in R

Preparing Video For Download...