简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM