Arrays R中数组上的if语句 用简单的方式陈述我的问题,考虑一下我有以下的功能: > ff<-function(a){ if (a>0){ return ("positive") } else{ return("negative") } }

Arrays R中数组上的if语句 用简单的方式陈述我的问题,考虑一下我有以下的功能: > ff<-function(a){ if (a>0){ return ("positive") } else{ return("negative") } },arrays,r,if-statement,Arrays,R,If Statement,使用阵列时: > print(ff(c(-1,1))) [1] "negative" "negative" Warning message: In if (a > 0) { : the condition has length > 1 and only the first element will be used 我期待着 print(ff(c(-1,1)))=("negative" "positive") 我该如何解决这个问题呢?您的函数没有矢量化,所以它不会像您期望

使用阵列时:

> print(ff(c(-1,1)))
[1] "negative" "negative"
Warning message:
In if (a > 0) { :
  the condition has length > 1 and only the first element will be used
我期待着

print(ff(c(-1,1)))=("negative" "positive")

我该如何解决这个问题呢?

您的函数没有矢量化,所以它不会像您期望的那样工作。您应该改用
ifelse
,它是矢量化的:

elements <- c(-1, 1, 1, -1)

ff <- function(a) {
  ifelse(a > 0, 'Positive', 'Negative')  
}

ff(elements)

[1] "Negative" "Positive" "Positive" "Negative"

elements您的函数没有矢量化,因此它不会像您期望的那样工作。您应该改用
ifelse
,它是矢量化的:

elements <- c(-1, 1, 1, -1)

ff <- function(a) {
  ifelse(a > 0, 'Positive', 'Negative')  
}

ff(elements)

[1] "Negative" "Positive" "Positive" "Negative"

elements或者,检查
dplyr
功能以了解更多信息


或者,也可以查看有关的
dplyr
功能


您还可以使用
symnum
cut
。你只需要定义合适的切点

symnum(elements, c(-Inf, 0, Inf), c("negative", "positive"))
negative positive positive negative

cut(elements, c(-Inf, 0, Inf), c("negative", "positive"))
[1] negative positive positive negative
Levels: negative positive
注:使用oriol mirosa答案中的
元素
向量:

elements <- c(-1, 1, 1, -1)

您还可以使用
symnum
cut
。你只需要定义合适的切点

symnum(elements, c(-Inf, 0, Inf), c("negative", "positive"))
negative positive positive negative

cut(elements, c(-Inf, 0, Inf), c("negative", "positive"))
[1] negative positive positive negative
Levels: negative positive
注:使用oriol mirosa答案中的
元素
向量:

elements <- c(-1, 1, 1, -1)
# convert elements vector to a matrix
elementsMat <- matrix(elements, 2, 2)
symnum(elementsMat, c(-Inf, 0, Inf), c("negative", "positive"))

[1,] negative positive
[2,] positive negative