2017-07-14 40 views
0

我是R的新手,想要学习如何制作一个简单的功能。 任何人都可以告诉我如何在R中复制这个相同的python加法函数吗?如何在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 
+0

你应该尝试从语法 – MIRMIX

回答

0

一直以为有关使更多的东西靠近你在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.') 
} 

在行动:

> 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. 

注意在R里面我们只有integernumericcomplex为基本数字数据类型。

最后,我不知道错误处理是否是你想要的,但希望它有帮助。

+0

非常感谢,看起来不错,非常有帮助! –

2

您可以在R中使用面向对象编程,但R主要是一种函数式编程语言。等效函数如下。

add <- function(x, y) { 

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

} 

注意:使用+已经做了你所要求的。

+0

开始学习R如果我正确地理解了它,你应该在你的测试中加入'is.complex()'。由于'is.numeric()'的结果应用于'complex'类型的变量,因此为'FALSE'。 –

+0

我已更新我的答案 – troh

+0

感谢您的帮助!这看起来很有趣!是的,我知道+符号,这绝对是最简单的方法!谢谢 –