[R] Creating dummy codes

Prof Brian Ripley ripley at stats.ox.ac.uk
Sun Aug 1 22:09:45 CEST 2004


On Sun, 1 Aug 2004, Doran, Harold wrote:

> Is there an efficient way to create a series of dummy codes from a
> single variable? For example, I have a variable, `grade' = {2, â¦,
> 12}. I want to create k-1 dummy codes for grade such that grade 2 is the
> base (i.e, grade 2 =0).

Yes, and that's what R does by default.

> I am hoping that the new variables can be labeled as grade.3, grade.4
> etc. I'll then use
> 
> grade <- paste("grade.", 3:12, sep="") in as.formula to build the model.

Why?  Just set the levels of your factor to 2:12 and R's default treatment 
contrasts do this for you.  To see this, just call model.matrix, as in

grade. <- as.factor(sample(2:12, 100, replace=T))
model.matrix(~grade.)[, -1]

but the R model fitting functions will do that for you.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list