mikeck
mikeck

Reputation: 3788

Redefine ? (help) function for certain classes

Is it possible to redefine the ? function (help function) for an R class?

I tried defining

`?.myclass` = function(x) "foo"
help.myclass = function(x) "foo"

but it doesn't change the behavior of ?.

f = function() "bar"
class(f) = "myclass"
?f                   # doesn't work
help(f)              # doesn't work
help.myclass(f)      #works

I am writing a package that uses PythonInR to import some Python functions. I was hoping I could add a class to the imported Python functions that would allow me to create a custom help function that called help(fun) in Python and print the results. I can write a python.help function that does this but I was hoping for a more seamless solution.

Upvotes: 1

Views: 85

Answers (1)

Florian
Florian

Reputation: 663

You could try something like the following:

library(PythonInR)

`?` <- function(e1, e2) UseMethod("?")
`?.default` <- utils::`?`

`?.pyFunction` <- function(e1, e2) {
    topicExpr <- substitute(e1)
    pyHelp(deparse(topicExpr))
}

pyImport("getcwd", from="os", as="os")

? os.getcwd

Furthermore you would need the following in your Namespace file.

export("?")
S3method("?", "default")
S3method("?", "pyFunction")

But for this function to work it is important that your function has the same name in Python and R.

I believe it would be maybe better you create .Rd files for your R functions.

Upvotes: 3

Related Questions