I am trying to write a function that lists the names of dataframes in my global environment.
I can do this by using the code:
l<-ls()
l[sapply(l, function(x) is.data.frame(get(x)))]
I need to convert this into a function that I can easily call upon.
You have to be aware that ls()
by default lists objects in the current environment. If you wrap your code in a function, this current environment is the internal function environment, which is empty at that point (we are at the first line of the function and nothing has been defined yet). Since you are interested in the global environment, you have to explicitly specify this with .GlobalEnv
:
lsf <- function() {
l<-ls(.GlobalEnv)
l[sapply(l, function(x) is.data.frame(get(x, envir = .GlobalEnv)))]
}
lsf()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With