Phạm vi và thứ tự ưu tiên

Nhập môn viết hàm trong R

Richie Cotton

Data Evangelist at DataCamp

Truy cập biến ngoài hàm

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
Nhập môn viết hàm trong R

Truy cập biến trong hàm từ bên ngoài

x_times_y <- function(x) {
  x * y
}
y <- 4
x_times_y(10)
print(x)
Error in print(x) : object 'x' not found
Nhập môn viết hàm trong R

Nên đặt biến ở đâu? Trong hay ngoài?

x_times_y <- function(x) {
  y <- 6
  x * y
}
y <- 4
x_times_y(10)
60
Nhập môn viết hàm trong R

Truyền vào vs. định nghĩa trong hàm

x_times_y <- function(x) {
  x <- 9
  y <- 6
  x * y
}
y <- 4
x_times_y(10)
54
Nhập môn viết hàm trong R

Ayo berlatih!

Nhập môn viết hàm trong R

Preparing Video For Download...