R - How to extract values โ€‹โ€‹for identical named elements for multiple objects of the same type?

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

+7
source share
3 answers

Q1) The code does not work because ls() looks into the environment of the function, and since there are no corresponding objects,

 paste0(ls()[grep(object, ls() )], "$", element) 

equivalently

 paste0("$", element) 

To get ls() to view in the workspace, you need ls(pos = 1) .

Q2) This is a common task, but, as far as is known, there is no function for this, because where the models, what they call, what objects you want to retrieve and how you want to return them, will depend on your requirements. A slightly tidier version of what you offer above will be

 nm <- paste0("model", 1:2) # adjust numbers as required unlist(lapply(nm, function(x) get(nm)$coef)) 

Alternatively, you can place your models in a list and use

 modList <- list(model1, model2) unlist(lapply(modList, "[[", "coefficients")) 
+12
source

You can use the map from the purrr package .

 l1 <- list(a1 = 3, a2 = 2) l2 <- list(a1 = 334, a2 = 34) l3 <- list(a1 = 90, a2 = 112) l <- list(l1, l2, l3) purrr::map(l, "a1") 

this gives:

 ### Result [[1]] [1] 3 [[2]] [1] 334 [[3]] [1] 90 
+3
source

This is the way to get the desired result:

 get.elements <- function(object, element) { unlist(lapply(ls(pattern = object, .GlobalEnv), function(x) get(x, .GlobalEnv)[[element, exact = FALSE]])) } 

Both element and object are character strings.

Note that I used the exact = FALSE argument, since the element is named coefficients , not coef . So you can use element = "coef" .

+2
source

All Articles