Reputation: 7113
hopefully this is not too simple. I am looking for a function which gives me the name of a function, which I assigned to a variable. So something like
x <- mean
the_function_i_look_for(x)
[1] "mean"
Any ideas? Many thanks in advance!
Edit:
Ok, this is a more detailed example: Actually I have a function where I pass an arbitrary logarithm and which gives me a data.frame back. One column name of the data frame should indicate which logarithm was used.
> myFunction <- function( log, x ) {
df <- data.frame( x, log(x))
names(df) <- c(the_function_i_look_for(log), "x")
return(df)
}
> myFunction( log10, c(10,100,1000) )
> log10 x
1 1 10
2 2 100
3 3 1000
Upvotes: 1
Views: 161
Reputation: 25736
You could use ?substitute
:
myFunction <- function( log, x ) {
df <- data.frame( x, log(x))
names(df) <- c("x", substitute(log))
return(df)
}
myFunction( log10, c(10,100,1000) )
# x log10
#1 10 1
#2 100 2
#3 1000 3
EDIT: Seems to work for ReferenceClasses, too:
foo <- setRefClass("foo",
methods = list(
bar = function(x) {
message("function: ", substitute(x))
}
))
f <- foo$new()
f$bar(log)
# function: log
f$bar(mean)
# function: mean
Upvotes: 3