【问题标题】:How to create similar python function in R?如何在 R 中创建类似的 python 函数?
【发布时间】:2017-07-14 14:40:41
【问题描述】:

我是 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

标签: python r function code-conversion


【解决方案1】:

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

add <- function(x, y) {

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

}

注意:使用 + 已经完成了您的要求。

【讨论】:

  • 如果我理解正确,您应该在测试中添加is.complex()。由于is.numeric() 应用于complex 类型的变量时的结果是FALSE
  • 也感谢您的帮助!看起来很有趣!是的,我知道 + 符号,这绝对是最简单的方法!谢谢
【解决方案2】:

考虑做一些更接近你在 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 作为基本数值数据类型。

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

【讨论】:

  • 非常感谢,这看起来很棒而且很有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-13
  • 1970-01-01
  • 2016-11-01
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 2018-10-06
相关资源
最近更新 更多