Warm tip: This article is reproduced from serverfault.com, please click
cut r

其他-使用CUT和四分位数在R函数中生成中断

(其他 - Using CUT and Quartile to generate breaks in R function)

发布于 2012-07-30 19:40:02

遵循之前的一些重要建议,我现在正在编写第二个R函数并使用类似的逻辑。但是,我正在尝试实现更多自动化,可能对我自己来说太聪明了。

我想根据订单数量将客户分成五等分。这是我这样做的代码:

# sample data
clientID <- round(runif(200,min=2000, max=3000),0)
orders <- round(runif(200,min=1, max=50),0)

df <- df <- data.frame(cbind(clientID,orders))

#function to break them into quintiles
ApplyQuintiles <- function(x) {
  cut(x, breaks=c(quantile(df$orders, probs = seq(0, 1, by = 0.20))), 
      labels=c("0-20","20-40","40-60","60-80","80-100"))
}

#Add the quintile to the dataframe
df$Quintile <- sapply(df$orders, ApplyQuintiles)

table(df$Quintile)

0-20   20-40   40-60    60-80   80-100 
40     39      44       38      36

你会在这里看到,在我的样本数据中,我创建了200个观测值,但通过列出的却只有197个table剩下的3个是NA

现在,有些clientID的五分位数为“ NA”。看来如果它们处于最低中断位置(在这种情况下为1),则它们不包含在cut函数中。

有没有办法cut包容所有观察结果?

Questioner
mikebmassey
Viewed
0
Edward 2012-07-31 03:49:06

请尝试以下方法:

set.seed(700)

clientID <- round(runif(200,min=2000, max=3000),0)
orders <- round(runif(200,min=1, max=50),0)

df <- df <- data.frame(cbind(clientID,orders))

ApplyQuintiles <- function(x) {
  cut(x, breaks=c(quantile(df$orders, probs = seq(0, 1, by = 0.20))), 
      labels=c("0-20","20-40","40-60","60-80","80-100"), include.lowest=TRUE)
}
df$Quintile <- sapply(df$orders, ApplyQuintiles)
table(df$Quintile)

0-20  20-40  40-60  60-80 80-100 
  40     41     39     40     40 

我包括include.lowest=TRUE在你的剪切功能中,这似乎可以使它正常工作。请参阅?cut以获取更多详细信息。