R function to transform continuous variable to categorical factor cut at n-tiles


The cut() function can be used to transform a continuous variable into a categorical factor variable. The syntax is quite lengthy and if one wishes to cut at quartiles, quintiles or other n-tiles one has to include the quantile() function into the call.

This is not very newbee friendly and if included into a model-call nearly unreadable.

The function in the code box cutN() does the job.

 cutN <- function(X , n = 4){
     cut(
         X ,
         include.lowest = TRUE ,
         breaks = quantile(
                           X , 
                           probs = (0:n)/n ,
                           na.rm = TRUE ))}

In order to cut the continuous variable Creatinine in the dataset Patients into deciles (n=10) the syntax is:
cutN( Patients$Creatinine , n = 10 )

No big deal, but maybe useful…

5 thoughts on “R function to transform continuous variable to categorical factor cut at n-tiles

  1. AH, this is exactly what I needed. Working on a survival analysis project and wanted to run the cox proportional hazard with one of the continuos variables split into quantiles. Thank you so much!

    1. Hi Kim, Did you have to install a package to make this work. I am getting an error: could not find function “cut.at.n.tile”

      1. 🙂 you have to copy-paste the code of the function into your script and run it once. Then R will find the function.

      2. I reformatted the old post a bit: Nowadays I tend to break lengthy oneliners with nice indentation for better readability. Also: cut.at.n.tiles was quite lengthy – changed to cutN

  2. Please can you confirm if the function cut.at.n.tile requires the installation of a particular package…

Leave a comment