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?
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!
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With