R: convert variable name to string in sapply

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

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

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

David

+4
source share
1 answer

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

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

Alternatively, iterate over 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 should not use deparse and substitute if you are not doing metaprogramming (if you do not know what it is, you do not).

+10
source

Source: https://habr.com/ru/post/1432837/


All Articles