R upvar variable to level above code example

Example: R upvar variable to level above

# Using <<- as opposed to <- in a function space will search for a variable of the same name in the level above. Example:
# This can help to return multiple variables out of a function
# An obvious alternative would be to return a list of desired outputs and separate afterwards.
# Nonetheless:
# Example:

# Make some blank variables at the top level:
global_numeric <- numeric();
global_list <- list();
# Make A function which uses <<- to return values
a_function <- function(number) {
  global_numeric <<- append(global_numeric, number);
  number_sq <- number*number;
  global_list <<-append(global_list, number_sq);
};

# Deploy Function:
for (i in 1:5) {
	a_function(i);
   	print(global_numeric);
    print(global_list);
};

Tags:

Misc Example