I have a series of objects storing the results of some statistical models in my workspace. Name them "model1", "model2", etc. Each of these models has the same set of named elements, for example, $ coef. I would like to select the values โโstored in a specific element from all objects containing the string "model" into a list or vector.
The following code entered on the command line does what I want:
unlist(lapply(parse(text = paste0(ls()[grep("model", ls() )], "$", "coef")), eval))
From this, I created the following general function:
get.elements <- function(object, element) { unlist(lapply(parse(text = paste0(ls()[grep(object, ls() )], "$", element)), eval)) }
However, when I run this function, I get the following error:
Error in parse(text = paste0(ls()[grep(object, ls() )], "$", element)) : <text>:1:1: unexpected '$' 1: $ ^
Q1. Why does this code work when run from the command line, but not as a function, and more importantly, how to fix it?
Q2. Even better, is there a simpler method that will do the same thing? This seems like such a common task for statisticians and simulators that I expect some kind of command in the base package, but I could not find anything. Of course, there should be a more elegant way to do this than my cumbersome method.
Thanks for the help.
- Dave