0

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
1
  • You should try to start learning R from syntax
    – MIRMIX
    Jul 14, 2017 at 14:51

2 Answers 2

3

You can use object oriented programming in R but R is primarily a functional programming language. An equivalent function is as follows.

add <- function(x, y) {

    stopifnot(is.numeric(x) | is.complex(x))
    stopifnot(is.numeric(y) | is.complex(y))
    x+y

}

Note: using + already does what you are asking.

2
  • If I understood it correctly you should have added is.complex() to your test. As the result of is.numeric() when applied to a variable of type complex is FALSE. Jul 14, 2017 at 14:49
  • Thanks for your help too! That looks interesting! And yes I'm aware of the + symbol, that's definitely the easiest method! Thanks Jul 14, 2017 at 22:51
-1

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.

1
  • Thanks a lot, that looks great and is very helpful! Jul 14, 2017 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.