Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Growing a list with variable names in R

Tags:

list

r

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?

like image 917
Amelio Vazquez-Reina Avatar asked Feb 10 '13 18:02

Amelio Vazquez-Reina


People also ask

How do I list variable names in R?

You can use ls() to list all variables that are created in the environment. Use ls() to display all variables. pat = " " is used for pattern matching such as ^, $, ., etc. Hope it helps!

Can you use numbers in variable names in R?

Variable Names Rules for R variables are: A variable name must start with a letter and can be a combination of letters, digits, period(.) and underscore(_). If it starts with period(.), it cannot be followed by a digit.

How do you assign a variable to a name in R?

In R, "assign('x',v)" sets the object whose name is 'x' to v. Replace 'x' by the result of applying a text function to a variable x. Then "assign" shows its worth.


1 Answers

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
like image 86
sebastian-c Avatar answered Oct 08 '22 16:10

sebastian-c