如何在R中创建类似的python函数?

时间:2017-07-14 14:40:41

标签: python r function code-conversion

我是R的新手,并试图学习如何制作一个简单的功能。 谁能告诉我如何在R中复制这个相同的python添加功能?

result <- LVector[LVector==LVectorTEMP] <- 0

2 个答案:

答案 0 :(得分:2)

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

add <- function(x, y) {

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

}

注意:使用+已经满足您的要求。

答案 1 :(得分:-1)

想想做一些与你在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作为基本数字数据类型。

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