Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

as.character usage on functions

Tags:

function

r

I stumbled uppon one problem:

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

yields an error. I undersand, why it is not possible to "convert" a function into a character. Question is, what properties to add to a function so that the method as.character returns a string defined by myself?

Thanks a lot!

like image 385
Drey Avatar asked Nov 22 '12 17:11

Drey


1 Answers

deparse can help:

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

Going further with the details of your comment, what you can do is create a class that derives function and pass this instead of the function.

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

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

f <- new( "myFunction", function(){} )
as.character(f)
# [1] "function () " "{"            "}"
like image 70
Romain Francois Avatar answered Sep 22 '22 01:09

Romain Francois