R - Access an object own's name in apply functions

Viewed 114

This is a problem I often encounters: I try to access an object's own name when using a function from apply family and spend hours figuring out how to do it... For instance (this is not the core of my question), today I was willing to inspect an attached package trying to figure out if it contained some non function objects. After a lot of tries and fails, I finally came up with (for the rrapply package - I know looking at the documentation is also easy but this one illustrates well the problem):

library(rrapply)

eapply(rlang::pkg_env('rrapply'), function(x) {if(!is.function(x)) x}) %>% 
`[`(sapply(., function(x) !is.null(x))) %>% 
names()

## [1] "renewable_energy_by_country" "pokedex" 

I feel that is really too complicated for a simple test !

So my question: is there an easy way to loop through an object in base R (or maybe tidyverse) and return only the names of those elements that correspond to a certain condition ? rrapply seems to be able to achieve that but:

  • it is fairly complicated
  • and it seems to work on lists only and to loop through all sub-elements as well which is not desired

Thanks !

1 Answers

Identify the environment of interest, e, and then use eapply with the indicated function taking the names of the extracted elements at the end. This isn't conceptually different from the code in the question but does seem somewhat less complex when done in base R in the following way:

e <- as.environment("package:rrapply")
names(Filter(`!`, eapply(e, is.function)))

or the same code written as a pipeline:

library(magrittr)

"package:rrapply" %>%
   as.environment %>%
   eapply(is.function) %>%
   Filter(`!`, .) %>%
   names
Related