5

I have found that to convert a variable name into a string I would use deparse(substitute(x)) where x is my variable name. But what if I want to do this in an sapply function call?

sapply( myDF, function(x) { hist( x, main=VariableNameAsString ) } )

When I use deparse(substitute(x)), I get something like X[[1L]] as the title. I would like to have the actual variable name. Any help would be appreciated.

David

2 Answers 2

11

If you need the names, then iterate over the names, not the values:

sapply(names(myDF), function(nm) hist(myDF[[nm]], main=nm))

Alternatively, iterate over both names and values at the same time using mapply or Map:

Map(function(name, values) hist(values, main=name),
    names(myDF), myDF)

For the most part, you shouldn't be using deparse and substitute unless you are doing metaprogramming (if you don't know what it is, you're not doing it).

Sign up to request clarification or add additional context in comments.

1 Comment

Yep. When using sapply, values are being passed without names.
2

Here is a piece of code that worked for me:

deparse(substitute(variable))

Comments

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.