Using as.character by function

I came across one problem:

temp.fun <- function() {} as.character(temp.fun) 

gives an error. I underestimate why it is impossible to "convert" a function to a character. The question is, what properties to add to the function so that the as.character method returns the string I defined?

Thanks a lot!

+6
source share
1 answer

deparse can help:

 > deparse( temp.fun ) [1] "function () " "{" "}" 

Going further with the details of your comment, you can create a class that outputs a function and passes this instead of a function.

 setClass( "myFunction", contains = "function" ) setMethod( "as.character", "myFunction", function(x, ...){ deparse( unclass( x ) ) } ) 

So, when you pass the function to a third-party package, you pass myFunction instead:

 f <- new( "myFunction", function(){} ) as.character(f) # [1] "function () " "{" "}" 
+7
source

All Articles