26

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.

6
  • 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--
    Commented Jul 18, 2017 at 20:28
  • 1
    have you looked at ls()?
    – bouncyball
    Commented Jul 18, 2017 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' Commented Jul 18, 2017 at 20:29
  • @bouncyball I thought about that, but OP says a data.frame not all of them.
    – M--
    Commented Jul 18, 2017 at 20:30
  • 1
    You may find something like what you want here: stackoverflow.com/questions/25509879/…. Perhaps the answer by MentatOfDune.
    – lmo
    Commented Jul 18, 2017 at 20:32

2 Answers 2

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

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.