R - 嵌套ifelse()语句中的Decile函数导致运行时间不佳

时间:2013-05-07 02:20:25

标签: r statistics quantile

我写了一个函数来计算向量中每行的十分位数。我这样做的目的是创建图形来评估预测模型的功效。必须有一种更简单的方法来做到这一点,但我暂时还没弄清楚。有没有人知道如何在没有这么多嵌套的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)),]

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分:1)

另一种解决方案是使用ecdf(),在帮助文件中描述为quantile()的反转。

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

请注意,@ mnel的解决方案快了大约100倍。