2017-07-14 39 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

感謝您的幫助!這看起來很有趣!是的,我知道+符號,這絕對是最簡單的方法!謝謝 –