How to correct the wrong result of the cut method?

Viewed 43

I'm trying to get five intervals of 150 samples but apparently the R cut method is giving me a wrong result. Below I leave the dataset and the code

age = c(89,81,59,80,74,36,28,73,44,51,31,75,31,60,42,16,38,76,72,67,47,31,63,45,58,78,45,90,41,53,24,47,41,24,59,
18,72,12,79,80,73,47,74,37,30,24,61,50,82,84,63,60,39,23,72,67,46,37,14,90,50,12,20,25,55,87,59,76,23,23,
36,61,19,65,42,80,23,41,20,77,20,52,54,33,38,53,71,78,71,12,77,40,80,23,45,58,73,24,50,15,81,61,59,33,37,
51,59,25,17,65,83,35,78,48,25,38,88,14,40,72,80,89,70,42,88,14,51,35,21,88,73,53,81,85,30,66,57,34,90,53,
40,80,76,24,33,69,81,52,35,33)

table((cut(age, breaks=5, right=FALSE, dig.lab=2))

# ---- results (wrong) ----
[12,28) [28,43) [43,59) [59,74) [74,90) 
     28      32      26      31      33 

the correct result is as shown in the following table

[12 - 28> [28 - 43> [43 - 59> [59 - 74> [74 - 90]
28 32 26 29 35
2 Answers

You choice of dig.lab just affects the labels for the levels, not the actual values for the the cuts. If you run

levels(cut(age, breaks=5, right=FALSE))
# [1] "[11.9,27.6)" "[27.6,43.2)" "[43.2,58.8)" "[58.8,74.4)"
# [5] "[74.4,90.1)"

You'll see that the actual breaks have decimal points. Those same breaks are used even when you change the labels with dig.lab. The dig.lab option is purely cosmetic.

If you want to use those exact breaks, you'll need to specify them yourself. For example

table(cut(age, breaks=c(12,38,43,59,74,90), right=FALSE, include.lowest = TRUE))
# [12,38) [38,43) [43,59) [59,74) [74,90] 
#      47      13      26      29      35 

An alternative (but only if you don't want those exact bins) for getting an equal number of observations with no decimal points is to use the ggplot2::cut_number() function. In your case, you could use:

library(ggplot2)
table(ggplot2::cut_number(age,5, right=FALSE, dig.lab=2))
#[12,30) [30,43) [43,59) [59,76) [76,90] 
#    29      31      26      32      32 
Related