Possible to call a function to all particular objects stored in project environment?

130 views Asked by At

I, stupidly, have been creating loads of new data_frames in an R project trying to solve a particular problem without making proper commits. Having gone through all practical names and most of the Greek alphabet, I now have an environment full of data_frame objects with names like 'bob','might.work','almostthere'. I'd like to use a looping function - lapply or otherwise - to return some indicators that will tell me something about each dataframe object in the environment. I can then clean up/delete based on the returns.

So is it possible to use lapply to access all data_frames in an R project environment? Something like this?

lapply(environment, function (x){
  if(is.dataframe(x)){
  dplyr::glimpse(x)
}
}

Thanks.

3

There are 3 answers

1
MrFlick On BEST ANSWER

The eapply() function easily iterates over objects in an environment

eapply(globalenv(), function(x) if (is.data.frame(x)) dplyr::glimpse(x))
0
Mark On

Sure is possible!

lapply(ls(),function(x){
  o = get(x,envir = globalenv())
  cat("if"(is.data.frame(o),paste0(x," is a data frame!\n"),"Nope.\n"))
})
  • ls() will list all object names in the environment (global by default).
  • Since this is just a name, we need to get the value but specify the global environment (since we're in a function environment at this point)
  • Then I cat out if it's a data frame, but you can do whatever you want with the o object.
0
Rui Barradas On

The following function will return the objects that inherit from class data.frame in the environment environ, which defaults to .GlobalEnv.

getDataFrames <- function(environ = .GlobalEnv){
    l <- ls(name = environ)
    res <- NULL
    for(i in seq_along(l)){
        r <- inherits(get(l[i], envir = environ), "data.frame")
        if(r) res <- c(res, l[i])
    }
    res
}

getDataFrames()