简体   繁体   English

如何在R中创建类似的python函数?

[英]How to create similar python function in R?

I'm new to R and trying to learn how to make a simple function. 我是R的新手,正在尝试学习如何制作简单的函数。 Could anyone advise me how to replicate this same python addition function in R please? 有人可以建议我如何在R中复制相同的python加法函数吗?

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. 您可以在R中使用面向对象的编程,但是R主要是一种功能编程语言。 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: 思考一下,使事情与您在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. 请注意,在R中,我们只有integernumericcomplex作为基本数字数据类型。

Finally, I do not know if the error handling is what you wanted, but hope it helps. 最后,我不知道错误处理是否是您想要的,但希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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