Answers for "R upvar variable to level above"

R
0

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);
};
Posted by: Guest on February-11-2021

Code answers related to "R upvar variable to level above"

Browse Popular Code Answers by Language