Growing a list with variable names in R

我怕爱的太早我们不能终老 提交于 2019-12-04 19:34:36

问题


I am trying to grow a list in R, where both the value and name of each entry is held in a variable, but it doesn't seem to work.

my_models_names <- names(my_models)
my_rocs=list() 
for (modl in my_models_names) {

    my_probs <- testPred[[modl]]$Y1
    my_roc <- roc(Ytst, my_probs)
    c(my_rocs, modl=my_roc) # <-- modl and my_roc are both variables
    }

My list my_rocs is empty at the end, even though I know that the loop iterates (my_roc is filled in) Why?

On a related note, is there a way to do this without looping?


回答1:


Generally in R, growing objects is bad. It increases the amount of memory used over starting with the full object and filling it in. It seems you know what the size of the list should be in advance.

For example:

my_keys <- letters[1:3]
mylist <- vector(mode="list", length=length(my_keys))
names(mylist) <- my_keys

mylist
## $a
## NULL

## $b
## NULL

## $c
## NULL

You can do assignment this way:

key <- "a"
mylist[[key]] <- 5
mylist
## $a
## [1] 5
##
## $b
## NULL
##
## $c
## NULL



回答2:


I found the answer on this thread.

I can grow a list using the following generic formula:

mylist <- list()

for (key in my_keys){ 
mylist[[ key ]] <- value # value is computed dynamically
}

In my OP:

  • mylist is my_rocs
  • key is modl
  • value is my_roc



回答3:


You can also use a more R-like soltution, and use lapply:

get_model = function(model_name) {
    my_probs <- testPred[[model_name]]$Y1
    return(roc(Ytst, my_probs))
  }
model_list = lapply(names(my_models), get_model)

Note that this solution saves you a lot of boilerplate code, it also does not suffer from the reallocation problem of your solution by growing the object. For large datasets, this can mean that the lapply solution is thousands of times faster.



来源:https://stackoverflow.com/questions/14801035/growing-a-list-with-variable-names-in-r

标签

工具导航Map