Rozsah platnosti a priorita

Introduction to Writing Functions in R

Richie Cotton

Data Evangelist at DataCamp

Přístup k proměnným mimo funkce

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

Přístup k proměnným funkce zvenčí

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

Co je lepší? Uvnitř, nebo vně?

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

Předaný parametr vs. definovaný uvnitř

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

Pojďme si to procvičit!

Introduction to Writing Functions in R

Preparing Video For Download...