[R] Basic Dummy Variable Creation

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Fri Sep 5 18:31:34 CEST 2003


Douglas Bates <bates at stat.wisc.edu> writes:

> > x <- c(1:10)      #data to be broken up into dummy variables
> > v <- c(3,5,7)     #breakpoints
> > p =  1                #drop this column to avoid dummy variable trap
> > 
> > How can I get a matrix "y" that has the associated dummy variables for
> > columns?
> 
> Don't.
> 
> Consider why you want the dummy variables.  You probably want to use
> them in the specification of a statistical model and R's model
> specification language automatically expands a factor variable into a
> set of contrasts.

... However, if you insist on seeing what goes on behind the scenes,
try

 x <- c(1:10)
 vv <- c(-Inf,v,Inf)
 f <- cut(x,vv)
 model.matrix(~f)
 model.matrix(~f)[,-1]
 model.matrix(~f-1)

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list