2013-07-30 38 views
3

我有概率的陣列在一個分類向量化「如果」中的R

post <- c(0.73,0.69,0.44,0.55,0.67,0.47,0.08,0.15,0.45,0.35) 

和我想要檢索的預測的類。 現在我用

predicted <- function(post) { 
       function(threshold) {plyr::aaply(post, 1, 
        function(x) {if(x >= threshold) '+' else '-'})}} 

,但似乎喜歡的事,R.將有一個語法。

是否有一些索引表達式會更直接?

+4

這必須是我見過的'ifelse'最複雜的實現。 :) – joran

+0

咦?你預計的功能應該是什麼? – Thomas

+1

@Thomas花了我一段時間:'預測(後)(0.5)'。 – joran

回答

6

由於@joran提示:

predicted <- function(post) 
    function(threshold) 
     ifelse(post>threshold,"+","-") 

我發現的功能有點混亂的嵌套結構。

ifelse(post>threshold,"+","-") 

似乎非常簡單,你甚至可能甚至不需要將它打包在一個函數中。

或者你可以使用

predicted <- function(post,threshold=0.5,alt=c("+","-")) 
     ifelse(post>threshold,alt[1],alt[2]) 

或者

predicted <- function(post,threshold=0.5,alt=c("+","-")) 
    alt[1+(post<=threshold)] 

很可能會稍快(post>threshold給出了一個合乎邏輯的載體,當添加到1被裹挾到0/1,導致1對於「低於」和2對「高於」)。或者你可以扭轉alt的順序,就像@DWin在他的回答中所做的那樣。

7
pred <- c("-", "+")[1+(post > 0.5)] 
+0

我剛剛添加一個... –

+3

我把它放在它,因爲它似乎是最矢量化。我認爲早些時候的SO調查顯示它在速度(和清晰度)方面不如'ifelse'。 –

+0

啊好方法! – nicolas