2017-07-29 50 views
0

在闡述我的問題的一個簡單的方法,可以考慮我有以下功能:如果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") 

我應該如何解決這個問題?

回答

0

你也可以使用symnumcut。你只需要定義適當的切割點。

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 
4

你的函數沒有被矢量化,所以它不會像你期望的那樣工作。您應該使用ifelse代替,這是矢量:

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

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

ff(elements) 

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

或者,檢查出dplyr功能more reliable behavior

a <- c(-1, 1, 1, -1) 

if_else(a < 0, "negative", "positive", "missing") 

這給:

[1] "negative" "positive" "positive" "negative"