Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write generic function with two inputs?

I am a newbee in programming, and I run into an issue with R about generic function: how to write it when there are multiple inputs?

For an easy example, for dataset and function

z <- c(2,3,4,5,8)
calc.simp <- function(a,x){a*x+8}
# Test the function:
calc.simp(x=z,a=3)
[1] 14 17 20 23 32

Now I change the class of z: class(z) <- 'simp' How should I write the generic function 'calc' as there are two inputs? My attempts and errors are below:

calc <- function(x) UseMethod('calc',x)
calc(x=z)
Error in calc.simp(x = z) : argument "a" is missing, with no default

And

calc <- function(x,y) UseMethod('calc',x,y)
Error in UseMethod("calc", x, y) : unused argument (y)

My confusion might be a fundamental one as I am just a beginner. Please help! Thank you very much!

like image 430
Branda Newbee Avatar asked Apr 03 '19 19:04

Branda Newbee


People also ask

How do you write a function with two inputs?

To create a function with two inputs, we just need to provide two different arguments inside function. For example, if we want to create a function to find the square of a+b then we can use x and y inside function.

Can a function take multiple inputs?

It means that a function can take multiple inputs but one simple case is taking two inputs. Define, def, myfunction. That is the name of a function, again, in the parenthesis. There are two input variables, x and y.

What is generic function give example?

Generics is the idea to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes and interfaces. For example, classes like an array, map, etc, which can be used using generics very efficiently. We can use them for any type.

How do you define a generic function?

Generic functions are true functions that can be passed as arguments, returned as values, used as the first argument to funcall and apply, and otherwise used in all the ways an ordinary function may be used.


1 Answers

I'd suggest you model your generic function off of the template used by innumerable base R functions as, e.g., mean:

> mean
function (x, ...) 
UseMethod("mean")

In your case, that would translate to the following generic which (if I understand your question correctly) works just fine:

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

calc.simp <- function(a, x) {
    x <- unclass(x)
    a * x + 8
}


## Try it out

z <- c(2,3,4,5,8)
class(z) <- "simp"

calc.simp(x = z, 10)
## [1] 28 38 48 58 88

calc(x = z, 10)
## [1] 28 38 48 58 88
like image 127
Josh O'Brien Avatar answered Sep 28 '22 03:09

Josh O'Brien