简体   繁体   中英

as.character usage on functions

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!

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 () " "{"            "}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM