Hos*_*her 0 arrays if-statement r
以简单的方式陈述我的问题,考虑我有以下功能:
> ff<-function(a){ if (a>0){ return ("positive") } else{ return("negative") } }
Run Code Online (Sandbox Code Playgroud)
现在:
> ff(-1)
[1] "negative"
> ff(1)
[1] "positive"
Run Code Online (Sandbox Code Playgroud)
而当使用数组时:
> 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
Run Code Online (Sandbox Code Playgroud)
我正期待着
print(ff(c(-1,1)))=("negative" "positive")
Run Code Online (Sandbox Code Playgroud)
我应该如何解决这个问题?
您的函数没有矢量化,因此它不会按您的预期工作。您应该使用ifelse矢量化的代替:
elements <- c(-1, 1, 1, -1)
ff <- function(a) {
ifelse(a > 0, 'Positive', 'Negative')
}
ff(elements)
[1] "Negative" "Positive" "Positive" "Negative"
Run Code Online (Sandbox Code Playgroud)