DSSS
DSSS

Reputation: 2051

Bin data into quantiles using cut - getting missing values

I have a dataframe:

a <- matrix(c(1,2,3,4), 2,2)
colnames(a) <- c("a", "b")
df <- as.data.frame(a)

> df
  a b
1 1 3
2 2 4

First, I calculate quartilies of "a" column:

> quantile (df$a)
  0%  25%  50%  75% 100% 
1.00 1.25 1.50 1.75 2.00 

Then, I would like to categorize column "b" using quartiles from column "a":

> cat.b<-cut(df$b, quantile (df$a,))
> cat.b  
[1] <NA> <NA>  
Levels: (1,1.25] (1.25,1.5] (1.5,1.75] (1.75,2]

As you can see, R gives NA for both "b" values as they are above the highest quartile of "a".

However, I would like the resulting "cat.b" vector to look like:

> cat.b
[1]
">2"    ">2"  

Could you please tell me how to do it in R.

Thank you

Upvotes: 0

Views: 2541

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70633

The two values are not in range. You can circumvent this by making another break. I chose Inf, you can use a finite value.

cat.b <- cut(df$b, c(-Inf, quantile(df$a), Inf))
#next line can be done better, but illustrates the purpose
levels(cat.b)[length(levels(cat.b))] <- ">2" 
levels(cat.b)[1] <- "<1"

cat.b
[1] >2 >2
Levels: (1,1.25] (1.25,1.5] (1.5,1.75] (1.75,2] >2

Upvotes: 5

Related Questions