Search code examples
pythonrfunctioncode-conversion

How to create similar python function in R?


I'm new to R and trying to learn how to make a simple function. Could anyone advise me how to replicate this same python addition function in R please?

def add(self,x,y):
    number_types = (int, long, float, complex)
    if isinstance(x, number_types) and isinstance(y, number_types):
        return x+y
    else:
        raise ValueError

Solution

  • Thinkin' about making something more close to what you did in Python:

    add <- function(x,y){
      number_types <- c('integer', 'numeric', 'complex')
      if(class(x) %in% number_types && class(y) %in% number_types){
        z <- x+y
        z
      } else stop('Either "x" or "y" is not a numeric value.')
    }
    

    In action:

    > add(3,7)
    [1] 10
    > add(5,10+5i)
    [1] 15+5i
    > add(3L,4)
    [1] 7
    > add('a',10)
    Error in add("a", 10) : Either "x" or "y" is not a numeric value.
    > add(10,'a')
    Error in add(10, "a") : Either "x" or "y" is not a numeric value.
    

    Notice that in R we only have integer, numeric and complex as basic numeric data types.

    Finally, I do not know if the error handling is what you wanted, but hope it helps.