zap*_*008 1 statistics r 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)),]
Run Code Online (Sandbox Code Playgroud)
你可以使用quantile和findInterval
# 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))
Run Code Online (Sandbox Code Playgroud)