R is a functional language, which generally means that you pass objects to functions and those functions return some object back, which you can do with as you wish. So, your intended result is a function like:
varNames <- function(existinglist, itemtoadd){
returnvalue <- c(existinglist, itemtoadd)
return(returnvalue)
}
listNames <- list()
a <- 'a'
varNames(existinglist = listNames, itemtoadd = a)
If you want to replace your original listNames
object with the return value of the function, then you need to assign it into that original object's name:
listNames
listNames <- varNames(existinglist = listNames, itemtoadd = a)
listNames
The way you've originally written your code is a common error among those new to R. You're trying to create what's known as a "side effect". That is, you want to modify your original listNames
object in place without using a <-
assignment. This is typically considered bad practice and there are relatively few functions in R that produce side effects like that.
To understand this better, you may find the R Introduction on scope and on assignment within functions helpful, as well as Circle 6 of R Inferno.