2013-05-07 102 views
1

我寫了一個函數來計算向量中每行的十進制數。我這樣做的目的是創建圖形來評估預測模型的功效。必須有一個更簡單的方法來做到這一點,但我暫時還沒有弄清楚。有沒有人有任何想法如何我可以用這種方式得到一個向量沒有這麼多嵌套ifelse()語句?我包含了函數以及一些代碼來複制我的結果。R中的Decile函數 - 嵌套的ifelse()語句導致運行時間不佳

# function 
decile <- function(x){ 
    deciles <- vector(length=10) 
    for (i in seq(0.1,1,.1)){ 
    deciles[i*10] <- quantile(x, i) 
    } 
    return (ifelse(x<deciles[1], 1, 
     ifelse(x<deciles[2], 2, 
       ifelse(x<deciles[3], 3, 
         ifelse(x<deciles[4], 4, 
           ifelse(x<deciles[5], 5, 
            ifelse(x<deciles[6], 6, 
              ifelse(x<deciles[7], 7, 
                ifelse(x<deciles[8], 8, 
                 ifelse(x<deciles[9], 9, 10)))))))))) 
} 

# check functionality 
test.df <- data.frame(a = 1:10, b = rnorm(10, 0, 1)) 

test.df$deciles <- decile(test.df$b) 

test.df 

# order data frame 
test.df[with(test.df, order(b)),] 

回答

5

您可以使用quantilefindInterval

# find the decile locations 
decLocations <- quantile(test.df$b, probs = seq(0.1,0.9,by=0.1)) 
# use findInterval with -Inf and Inf as upper and lower bounds 
findInterval(test.df$b,c(-Inf,decLocations, Inf)) 
+0

這似乎工作正常,但我會通過它真正快速工作,並確保我明白它。我從來沒有用過findInterval()。 – zap2008 2013-05-07 02:44:33

+0

mnel的答案完美。 @Matthew,'all.inside = T'選項不起作用,因爲decLocations向量只能達到第90個百分點。如果您想使用all.inside,您需要將第一行更改爲: 'decLocations < - quantile(test.df $ b,probs = seq(0.1,1,by = 0.1))' – zap2008 2013-05-07 02:59:08

+0

You are correct ,Zap(就像mnel一樣)。我錯過了他將參數更改爲'seq'。 – 2013-05-07 03:04:56

1

另一種解決方案是使用ecdf(),在幫助文件中描述爲quantile()倒數。

round(ecdf(test.df$b)(test.df$b) * 10) 

請注意,@ mnel的解決方案快100倍左右。