23

How can I extract the name of a data.frame in R as a character?

For example, if I have data.frame named df, I want to get "df" as a character object.

M--
  • 25,431
  • 8
  • 61
  • 93
Gaurav Bansal
  • 5,221
  • 14
  • 45
  • 91
  • 1
    What do you mean by extract? If you already know its name is `df` then use `'df'` and it will give you the character. From where? – M-- Jul 18 '17 at 20:28
  • 1
    have you looked at `ls()`? – bouncyball Jul 18 '17 at 20:29
  • I want to extract the name of the dataframe and save it as an object. For example, `name_of_dataframe` should be a character object that contains 'df' – Gaurav Bansal Jul 18 '17 at 20:29
  • @bouncyball I thought about that, but OP says ***a*** `data.frame` not all of them. – M-- Jul 18 '17 at 20:30
  • 1
    You may find something like what you want here: https://stackoverflow.com/questions/25509879/how-can-i-make-a-list-of-all-dataframes-that-are-in-my-global-environment. Perhaps the answer by MentatOfDune. – lmo Jul 18 '17 at 20:32
  • Do you mean what is the original variable name of a data.frame parameter of a function? – HubertL Jul 18 '17 at 20:38

2 Answers2

50
a <- data.frame()
deparse(substitute(a))
[1] "a"

This is also how plot knows what to put on the axes

Vandenman
  • 3,046
  • 20
  • 33
7

If you've got more than one dataframe that you want to retrieve the name of, you can use ls.str(mode = "list"). We use list because dataframes are stored as lists.

For example:

# make two dataframes
mydf1 <- data.frame(a = letters[1:10], b = runif(10))
mydf2 <- data.frame(a = letters[1:10], b = runif(10))

# see that dataframes are stored as lists:
storage.mode(mydf1)
[1] "list"

# store the names of the dataframes
names_of_dataframes <- ls.str(mode = "list")

# see the name of the first dataframe
names_of_dataframes[1]
[1] "mydf1"

# see the name of the second dataframe
names_of_dataframes[2]
[1] "mydf2"

Note that this method will also include the names of other list objects in your global environment. ls.str allows you to select the environment you want to search so you could store your dataframes in a different environment to other list objects.

meenaparam
  • 1,949
  • 2
  • 17
  • 29