Global vs. Local Data Objects in R Programming (2 Examples)
In this article, I’ll explain how to define global and local data objects in the R programming language.
Example 1: Using <- within User-Defined Function [Local Environment]
fn1 <- function() { # Create own function using <- my_result_1 <- 555 } |
fn1 <- function() { # Create own function using <- my_result_1 <- 555 }
fn1() # Apply own function |
fn1() # Apply own function
my_result_1 # Try to print data object outside of function # Error: object 'my_result_1' not found |
my_result_1 # Try to print data object outside of function # Error: object 'my_result_1' not found
Example 2: Using <<- within User-Defined Function [Global Environment]
fn2 <- function() { # Create own function using <<- my_result_2 <<- 555 } |
fn2 <- function() { # Create own function using <<- my_result_2 <<- 555 }
fn2() # Apply own function |
fn2() # Apply own function
my_result_2 # Print data object outside of function - works fine # 555 |
my_result_2 # Print data object outside of function - works fine # 555