我是 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
考虑做一些更接近你在 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 中,我们只有integer
,numeric
和complex
作为基本数字数据类型。
最后,我不知道错误处理是否是您想要的,但希望它有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句