Question

I am a newbie in R trying to write a function to add elements to a list.

Below is the code for the function varNames. I can call it with varNames("name1") but "name1" is not added to "listNames" (this still remains as an empty list).

I've been trying a few things, and searching for answers for a long time, with no success.

Also tried lappend, with no success.

listNames<-list()

varNames<- function(name){

  listNames <- c(listNames, name)

}
Était-ce utile?

La solution

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.

Autres conseils

The problem is with scope. The listNames in the function is local to that function. Essentially, it is a different object from the listNames you want to change.

There are a few ways to get around this:

  1. Change the value of listNames to the output of the function varNames():

    listNames <- varNames(name)
    
  2. Use <<- and get() to change the value of the listNames in the outer scope. This is generally a bad idea as it makes debuggin very hard.

  3. Don't encapsulate the c() function in the first place.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top