The issue here is variable scoping. The variable meals
exists in your global environment where you are using it. When you run your function, there is no meals
variable inside the function environment, so it inherits that variable from the global environment. However, when it modifies the variable, it creates a new version inside the function environment. The function can then use that modified version, but it never changes the meals
variable from the global environment.
So, you can use the function as it is currently written, and just save the result to meals
like so:
meals <- add("Steak")
The value is returned invisibly when you save it to a variable at the end of your function, but it does still output (like the full result of lm
or hist
that are only accessible if you save them to a new variable). This is one reason why it is a good idea to get in the habit of always ending functions with an explicit return
or invisible
statement.
My guess is that you are coming from a different programming language where changing a global variable inside a function changes the variable globally. That behavior by explicitly telling R to override that environmental behavior with <<-
, which assigns the value outside of the current environment (instead of just within it). For example, this:
add <- function(str) {
meals <<- append(meals, as.character(str))
}
meals <- "Steak"
add("Chicken")
meals
results in meals
holding both "Steak" and "Chicken" -- the behavior you want. HOWEVER, this is generally a bad idea in R. There are times when this behavior is nice, but the fact that it is very different from how R generally operates leaves a lot of opportunity for mistakes to slip in. I use this occasionally to get past scoping issues (often when working in shiny
and needing to change things for the whole session, rather than just the current user), but I try to avoid it if at all possible.
I would encourage you to, instead, just use the construction:
meals <- append(meals, str)
directly, rather than trying to wrap this in a custom function that works so differently than standard R approaches.