[R] Calling any method within default method!

Ivan Bezerra Allaman |v@n@|@m@n @end|ng |rom gm@||@com
Wed May 29 01:34:07 CEST 2019


Good night dear!
For years I have a problem that I have avoided with the use of the switch
function, but now I want to solve by following the good practices of object
orientation (OOP).
My function was created to generate experiments according to some input
parameters. Therefore, the first argument does not have a class defined as
"data.frame", "matrix", etc., so that from the generic, specific methods can
be called.
I made a simple example to show my problem.

foo <- function (x, ...) UseMethod ('foo')

foo.default <- function(x,
                        a = 10,
                        b = NULL,
                        cc = 2,
                        dd = 3,
                        type = c ('brazil', 'argentina'),
                        ...){

  ty <- match.arg(type)

  obj <- list(a = a,
                 b = b,
                 cc = cc,
                 dd = dd)
  class (obj) <- paste ('foo',
                                   ty,
                                  sep = '.')

  res <- foo(x = obj, ...)
}

foo.brazil <- function(x, ...){
  a <- x$a
  cc <- x$cc
  res <- a + cc
  return (res)
}

foo.argentina <- function(x, ...){
  cc <- x$cc
  dd <- x$dd
  res <- sqrt(cc + dd)
  return (res)
}

foo(a = 1)

If anyone has any light I thank them immensely.

-- 
\begin{signature}
<<>>=
Prof. D.Sc. Ivan Bezerra Allaman
Laboratório de Estatística Computacional
Departamento de Ciências Exatas e Tecnológicas
Universidade Estadual de Santa Cruz

Ilhéus/BA - Brasil
Fone: +55 73 3680-5622
E-mail:ivanalaman using gmail.com
@
\end{signature}

	[[alternative HTML version deleted]]



More information about the R-help mailing list