ขอบเขตและลำดับความสำคัญ

Introduction to Writing Functions in R

Richie Cotton

Data Evangelist at DataCamp

การเข้าถึงตัวแปรจากภายนอกฟังก์ชัน

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

การเข้าถึงตัวแปรภายในฟังก์ชันจากภายนอก

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

ควรกำหนดไว้ข้างในหรือข้างนอกดี?

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

อาร์กิวเมนต์ที่ส่งเข้า vs. ที่กำหนดภายใน

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

มาฝึกกันเถอะ!

Introduction to Writing Functions in R

Preparing Video For Download...