I have a series of objects storing the results of some statistical models in my workspace. Call them "model1", "model2", etc. Each of these models has the same set of named elements attached, $coef, for example. I would like to extract into a list or vector the values stored in a particular element from all objects containing the string "model".
The following code entered at the command line does what I want:
unlist(lapply(parse(text = paste0(ls()[grep("model", ls() )], "$", "coef")), eval))
From this, I've created the following generic 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 do I fix it?
Q2. Even better, is there a simpler method that will accomplish the same thing? This seems like such a common task for statisticians and simulation modelers that I would expect some kind of command in the base package, yet I've been unable to find anything. Surely there must be a more elegant way to do this than my cumbersome method.
Thanks for all help.
--Dave
m[["coefficients"]]
, so you could just dom[[element]]
. Also, keeping multiple models as variables namedmodel1
,model2
is a poor choice: you should keep them as a list of models. That way, you can get the coefficients like this:lapply(models, function(m) m[[element]])