0

my question is how can I get the name of a dataframe not the colnames

for example d is my dataframe I want to use a function to get the exact name "d" rather than the results from names(d)

Thank you so much!

Update:

The reason why I am asking this is because I want to write a function to generate several plots at one time. I need to change the main of the plots in order to distinguish them. My function looks like fct=function(data){ cor_Max = cor(data) solution=fa(r = cor_Max, nfactors = 1, fm = "ml") return(fa.diagram(solution,main=names(data)) }

How can I change the main in the function correspondingly to the data's name?

4 Answers 4

3

You can use the fact that R allows you to obtain the text representation of an expression:

getName <- function(x) deparse(substitute(x))
print(getName(d))
# [1] "d"
Sign up to request clarification or add additional context in comments.

1 Comment

but actually it seems not working when the dataframe is an argument in the function, please see the update
0

objects() will list all of the objects in your environment. Note that names(), as used in your question, provides the column names of the data frame.

1 Comment

Just a note, names is not just for column names. It can be used on vectors as well.
0

I read your question to say that you are looking for the name of the data frame, not the column names. So you're looking for the name passed to the data argument of fct. If so, perhaps something like the following would help

fct  <- function(data){
 cor_Max  <-  cor(data)
 # as.character(sys.call()) returns the function name followed by the argument values
 # so the value of the "data" argument is the second element in the char vector
 main <-  as.character(sys.call())[2]
 print(main)
 }

This is a bit ad hoc but maybe it would work for your case.

Comments

0

The most accepted way to do this is as Robert showed, with deparse(substitute(x)). But you could try something with match.call()

f <- function(x){
    m <- match.call()
    list(x, as.character(m))
}

> y <- 25
> f(y)
# [[1]]
# [1] 25
#
# [[2]]
# [1] "f" "y"

Now you've got both the value of y and its name, "y" inside the function environment. You can use as.character(m)[-1] to retrieve the object name passed to the argument x

So, your function can use this as a name, for example, like this:

fct <- function(data){
    m <- match.call()
    plot(cyl ~ mpg, data, main = as.character(m)[-1])
}

> fct(mtcars)

1 Comment

hi @RichardScriven please see my update I know how to get the name of the dataframes in the overall environment but I don't know how to access that in a function.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.