9

How do I get vector of data frame names available in current environment? I've tried:

sapply(ls(), is.data.frame)

But this fails because ls returns vector of strings. I'm planning to use this list as a input for dynamic selection in Shiny app.

Tomas Greif
  • 21,685
  • 23
  • 106
  • 155
  • 2
    I use a modified `lsos()` function based on [this question](http://stackoverflow.com/questions/1358003/tricks-to-manage-the-available-memory-in-an-r-session) – Ricardo Saporta Oct 30 '13 at 14:25

4 Answers4

19

You can use eapply to loop through the objects in an environment:

x <- 1:10
y <- mtcars
eapply(.GlobalEnv,is.data.frame)
$x
[1] FALSE

$y
[1] TRUE

names(which(unlist(eapply(.GlobalEnv,is.data.frame))))
[1] "y"
James
  • 65,548
  • 14
  • 155
  • 193
  • 3
    This is nice. Careful with that last line though, it will only work properly in the global environment since `eapply()` is explicitly targeting `.GlobalEnv` whereas `ls()` isn't (won't work right in a function). Could do something like: `names(Filter(isTRUE, eapply(.GlobalEnv, is.data.frame)))` then there's no need for `ls()` or `unlist()`. – Ciarán Tobin Oct 30 '13 at 16:59
  • @MadScone Yes, I was a little lax with the last line. I have put an alternative in now. – James Oct 30 '13 at 17:19
6

I think you're asking for the actual names of these data frames rather than the data frames themselves? You can do:

l <- ls()
l[sapply(l, function(x) is.data.frame(get(x)))]

get() will return the value of an object given a character name.


Tidier way of doing basically the same thing:

Filter(function(x) is.data.frame(get(x)), ls())
Ciarán Tobin
  • 7,306
  • 1
  • 29
  • 45
5

You need get, try this:

x <- sapply(sapply(ls(), get), is.data.frame)
names(x)[(x==TRUE)] 
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
3

I use a modified lsos() function based on this question

library(devtools)
source_url("https://raw.github.com/rsaporta/pubR/gitbranch/memoryFunctions.R")

## only show data.frames of at least ~1KB
lsos(t="data.frame")

## show data.frames of any size
lsos(t="data.frame", b=1)

### OUTPUT

           KB       Type Rows Columns
anotherDF   5 data.frame   50       4
df        0.8 data.frame    5       2
Community
  • 1
  • 1
Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178