如果R中数组声明
问题描述:
在阐述我的问题的一个简单的方法,可以考虑我有以下功能:如果R中数组声明
> ff<-function(a){ if (a>0){ return ("positive") } else{ return("negative") } }
现在
:
> ff(-1)
[1] "negative"
> ff(1)
[1] "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")
我应该如何解决这个问题?
答
你也可以使用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
注:从奥里奥尔 - mirosa的答案使用elements
载体:
elements <- c(-1, 1, 1, -1)
作为一个令人兴奋的一边,symnum
将与矩阵以及工作:
# 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
答
你的函数没有被矢量化,所以它不会像你期望的那样工作。您应该使用ifelse
代替,这是矢量:
elements <- c(-1, 1, 1, -1)
ff <- function(a) {
ifelse(a > 0, 'Positive', 'Negative')
}
ff(elements)
[1] "Negative" "Positive" "Positive" "Negative"
答
或者,检查出dplyr
功能more reliable behavior。
a <- c(-1, 1, 1, -1)
if_else(a < 0, "negative", "positive", "missing")
这给:
[1] "negative" "positive" "positive" "negative"