簡體   English   中英

如何在R中創建類似的python函數?

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

我是R的新手,正在嘗試學習如何制作簡單的函數。 有人可以建議我如何在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

您可以在R中使用面向對象的編程,但是R主要是一種功能編程語言。 等效功能如下。

add <- function(x, y) {

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

}

注意:使用+已經可以滿足您的要求。

思考一下,使事情與您在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作為基本數字數據類型。

最后,我不知道錯誤處理是否是您想要的,但希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM