Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Convert variable name to string in sapply

Tags:

r

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

like image 823
dmonder Avatar asked Dec 27 '22 18:12

dmonder


1 Answers

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).

like image 133
Ryan C. Thompson Avatar answered Jan 01 '23 19:01

Ryan C. Thompson