๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R Scope

Scope is the set of places in a script where a name can be seen and used.

An outside value is visible inside

The value bonus sits outside the function. The function reads that outside value and adds it to its input.

bonus <- 5
add_bonus <- function(num) {
  num + bonus
}
print(add_bonus(10))

A local assignment stays local

The assignment inside the function makes a local x. The outside x still holds 10 after the call.

x <- 10
change_x <- function() {
  x <- 99
  print(x)
}
change_x()
print(x)

A local name does not exist outside

The name secret is created only inside the function. Printing that name outside the function gives an error.

make_secret <- function() {
  secret <- 42
  secret + 0
}
made <- make_secret()
print(secret)

Example

tax <- 5
add_tax <- function(amount) {
  amount + tax
}
print(add_tax(20))
print(tax)

Key points

  • A value made outside a function is visible inside the function.
  • An assignment inside a function makes a local value with that name.
  • The local value lives only while the call runs.
  • A local assignment leaves an outside value with the same name untouched.
  • A name created only inside a function does not exist outside the function.

In this example, add_tax reads the outside value tax and adds it to its argument. The outside value tax still holds 5 after the call.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

A function assigns x <- 99 while an outside x holds 10. What does the outside x hold after the call?