Growing a list with variable names in R

I am trying to grow a list in R, where both the value and the name of each record are stored in a variable, but it does not 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 empty at the end, although I know the iteration loop ( my_roc full). Why?

In the corresponding note, is there a way to do this without a loop?

+6
source share
3 answers

I found the answer to this thread .

I can make a list using the following general formula:

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

In my OP:

  • mylist my_rocs
  • key modl
  • value my_roc
+2
source

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

For instance:

 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 complete the assignment as follows:

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

You can also use a more R-shaped solution 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) 

Please note that this solution will save you a lot of template code, it also does not suffer from the problem of redistributing your solution by growing the object. For large datasets, this may mean that the solution is lapply thousands of times faster.

+3
source

All Articles