RockScience
RockScience

Reputation: 18580

define a S4 method if there is already a function with the same name

I have a function myFunction and I need to create a S4 method with the same name (do not ask me why).
I would like to keep the old functionality of myFunction.

Is there a way to keep my old function?

I would rather not set a generic for this old function as the signature may be very different...

Upvotes: 2

Views: 570

Answers (1)

Josh O'Brien
Josh O'Brien

Reputation: 162321

Yes, there is a way to keep your old function. And unless you want both the S3 and S4 functions to accept the same number of arguments of the same classes, it's not even complicated to do.

# Create an S3 function named "myFun"
myFun <- function(x) cat(x, "\n")

# Create an S4 function named "myFun", dispatched when myFun() is called with 
# a single numeric argument
setMethod("myFun", signature=signature(x="numeric"), function(x) rnorm(x))

# When called with a numeric argument, the S4 function is dispatched
myFun(6)
# [1]  0.3502462 -1.3327865 -0.9338347 -0.7718385  0.7593676  0.3961752

# When called with any other class of argument, the S3 function is dispatched
myFun("hello")
# hello 

If you do want the S4 function to take the same type of argument as the S3 function, you'll need to do something like the following, setting the class of the argument so that R has some way of divining which of the two functions you are intending it to use:

setMethod("myFun", signature=signature(x="greeting"), 
          function(x) cat(x, x, x, "\n"))

# Create an object of class "greeting" that will dispatch the just-created 
# S4 function
XX <- "hello"
class(XX) <- "greeting"
myFun(XX)
# hello hello hello 

# A supplied argument of class "character" still dispatches the S3 function
myFun("hello")
# hello

Upvotes: 6

Related Questions