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

6 11 2011

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…

Advertisements

Actions

Information

5 responses

17 07 2012
Kim

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!

19 05 2016
ADE AWONAIKE

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”

19 05 2016
rforge

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

19 05 2016
rforge

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

19 05 2016
ADE AWONAIKE

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: