[R] Creating a sequence of variables in a data frame

ripley@stats.ox.ac.uk ripley at stats.ox.ac.uk
Mon Mar 10 09:14:54 CET 2003


On Mon, 10 Mar 2003, Jason Turner wrote:
> On Mon, Mar 10, 2003 at 01:08:43AM -0500, Ryan T. Moore wrote:

[...]
> > 2.  If I have a variable in a data frame, is there quick bit of code
> > that creates a dummy variable for each level of that variable? 
> 
> Depends what you mean by "quick" ... ;).  I'm sure Thomas Lumley could
> blast out a one-liner with reshape() that does exactly what you need,
> but I'm pretty clunky with those.  I'd use the above, and roll it
> through another loop.
> 
> for(jj in 1:5) { 
>   foo[[jj + 1]] [which(foo$old == jj)] <- TRUE #note - same offset
>                                                #from above
> }

You don't need the which(), as logical indices are just as good.

library(nnet)
?class.ind

(That returns a numeric matrix with 0/1, which is how I understand dummy 
variables are usually coded.  You could also use model.matrix(~ foo - 1).)

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