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 ufnreadable.

The function in the code box cut.at.n.tile() does the job.


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

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

No big deal, but maybe useful…

About these ads

Actions

Information

One response

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!

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 )

Connecting to %s




Follow

Get every new post delivered to your Inbox.

%d bloggers like this: