スコープと優先順位

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
R関数入門

関数内の変数を外から参照する

x_times_y <- function(x) {
  x * y
}
y <- 4
x_times_y(10)
print(x)
Error in print(x) : object 'x' not found
R関数入門

最適なのは内か外か?

x_times_y <- function(x) {
  y <- 6
  x * y
}
y <- 4
x_times_y(10)
60
R関数入門

引数で渡す vs. 関数内で定義

x_times_y <- function(x) {
  x <- 9
  y <- 6
  x * y
}
y <- 4
x_times_y(10)
54
R関数入門

Let's practice!

R関数入門

Preparing Video For Download...