renvironments

Binding values from function to global environment in R


I'm having trouble understanding how to bind values from within a function to an environment outside of the function. A basic example is shown below, I cannot seem to solve the last part of the function:

number <- data.frame()

how_many_fruits <- function() {

    answer <- as.integer(readline(prompt="How Many?: "))
    globalenv()$number <- rbind(globalenv()$number, answer)

}

Essentially, I want to have an empty data frame called number in the beginning, and every time how_many_fruits() is run, I want the input to be attached to the bottom of the number data frame.


Solution

  • You can use the <<- operator:

    number <- data.frame()
    how_many_fruits <- function() {
    
      answer <- as.integer(readline(prompt="How Many?: "))  
      number <<- rbind(number, answer)
    
    }
    

    However, I wonder what your goal is with that procedure. A function should not use variables in the global environment in the way you do. What will happen, if someone wants to use that function, but calls the variable num instead of number? The function won't work in that situation. So I would suggest that you do the following instead:

    how_many_fruits <- function(num) {
    
      answer <- as.integer(readline(prompt="How Many?: "))
      new_num <- rbind(num, answer)
    
      return (new_num)
    }
    
    number <- data.frame()
    number <- how_many_fruits(number)
    

    This is how a function is supposed to work: it takes inputs (here called num) and it returns an output (here called new_num). Note how the name of the input and output inside the function need not be the same as the name of the variables you use outside the function. When you call how_many_fruits(number), the contents of number are stored in num and the function only works with the latter. And when you do number <- how_many_fruits(number), whatever is returned as the result of how_many_fruits(number) is stored in number.