# [R] S4 method selection based on second argument

Witold Eryk Wolski wolski at molgen.mpg.de
Wed Sep 29 00:24:12 CEST 2004

```Hi,
If it's the only reason why you think you have to use S4 then take a
look at ?missing.
If you are interested in S4:
The first version gives an overview of setMethods. Then I give a simpler
example. And finally a pure ?missing solution.

A) Declare function repmat as generic
if(!isGeneric("repmat"))
setGeneric("repmat"
,function(obx,oby,obz,...)
standardGeneric("repmat"))

#B = repmat(A, m, n)

setMethod("repmat",signature(obx="numeric",oby="numeric",obz="numeric")
,function(obx,oby,obz){print("thre arg call")
})

#B = repmat(A, [m n])
#B = repmat(A, n)

setMethod("repmat",signature(obx="numeric",oby="numeric",obz="missing")
,function(obx,oby)
{
print("two arg")
#handle the difference in oby.
if(length(oby)==1)
oby
else
obx
})

##END A ###
#simpler

#if(!isGeneric("repmat")) #commented out because you have already declared it.
setGeneric("repmat"
,function(object,...)
standardGeneric("repmat"))

setMethod("repmat",signature(object="numeric")
,function(object,oby,obz)
{
#using ?missing handle the differences.
if(missing(obz))
print("new version")
})

Note that you can have the same in S3 using ?missing
something like this.

repmat <- function(A, m, n) {
if(missing(n)
{
if(length(m)==2)
{
repmat1(A, m[1], m[2])
}
else
kronecker(matrix(1, m, m), A)
}
kronecker(matrix(1, n, m), A)}
}
/E

Paul Roebuck wrote:

>I'm translating some Matlab code and need some help figuring
>out how to change this call into an S4 generic method.
>
>In matlab, there's a function called 'repmat' with three
>calling sequences (all I have to deal with anyway):
>    1) B = repmat(A, m, n)
>    2) B = repmat(A, [m n])
>    3) B = repmat(A, n)
>In all cases, A is the fill value, m is number of rows,
>and n is number of columns.
>
>As separate functions, the translations would roughly be:
>
>repmat1 <- function(A, m, n) {
>    kronecker(matrix(1, n, m), A)
>}
>
>

>repmat2 <- function(A, rc) {
>    repmat1(A, rc[1], rc[2])
>}
>
>repmat3 <- function(A, n) {
>    repmat1(A, n, n)
>}
>
>Suggestions?
>
>
>----------------------------------------------------------
>SIGSIG -- signature too long (core dumped)
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>
>
>

--
Dipl. bio-chem. Witold Eryk Wolski
MPI-Moleculare Genetic
Ihnestrasse 63-73 14195 Berlin           _
tel: 0049-30-83875219                   'v'
http://www.molgen.mpg.de/~wolski       /   \
mail: witek96 at users.sourceforge.net  ---W-W----
wolski at molgen.mpg.de

```