Warning When using regular expressions, this solution may fail under certain conditions (depending on the names you use in your lists). If speed is not an option, either list.map or a solution using sapply more reliable
You can get pretty high speed using unlist() here and look for names. Take the following function myselect :
myselect <- function(x,name){ tmp <- unlist(x,recursive=FALSE) id <- grep(paste0("(^|\\.)",name,"$"),names(tmp)) tmp[id] }
This is done in much the same way, but in vector form. Using the recursive=FALSE argument, you insert a nested list into a flat list (all elements are part of the same list). You then use the naming convention used by this function to search for all elements containing the exact name you want to select. Therefore, calling paste0 to create a regular expression that avoids matching the partial name. A simple selection returns you a list with the necessary items again. If you want it to be a vector or so, you can simply use unlist() for the result.
Please note that I assume you have a list of lists, so you only want to flatten one level. For a more complex investment, this obviously will not work in the current form.
Example and benchmarking
The gain probably depends on the structure of the list, but can reach a 50x or greater increase in speed.
Take the following (very simple) example:
aList <- list( a=list(x=rnorm(10),y=letters[1:10],z="OK"), b=list(x=rnorm(10),y=letters[11:20],z="notOK") )
Benchmarking gives:
require(rbenchmark) benchmark( sapply(aList,function(i)i$z), myselect(aList,"z"), columns=c("test","elapsed","relative"), replications=10000 ) test elapsed relative 2 myselect(aList, "z") 0.24 1.000 1 sapply(aList, function(i) i$z) 0.39 1.625
With larger objects, improvement can be significant. Using this on the list that I happened to have in my workspace (dput is not an option here ...):
> benchmark( + sapply(StatN0_1,function(i)i$SP), + myselect(StatN0_1,"SP"), + columns=c("test","elapsed","relative"), + replications=100 + ) test elapsed relative 2 myselect(StatN0_1, "SP") 0.02 1.0 1 sapply(StatN0_1, function(i) i$SP) 1.13 56.5