[R] Help with contrasts

peter dalgaard pdalgd at gmail.com
Wed May 11 13:30:36 CEST 2011


On May 11, 2011, at 12:51 , Lars Bishop wrote:

> Hi,
> 
> I need to build a function to generate one column for each level of a factor
> in the model matrix created on an arbitrary formula (instead of using the
> available contrasts options such as contr.treatment, contr.SAS, etc).
> 
> My approach to this was first to use the built-in function for
> contr.treatment but changing the default value of the contrasts argument to
> FALSE (I named this function "contr.identity" and it shown at the bottom of
> the email for reference).
> 
> So this function works fine,
> 
>> contr.identity(4)
> 
>  1 2 3 4
> 1 1 0 0 0
> 2 0 1 0 0
> 3 0 0 1 0
> 4 0 0 0 1
> 
>> contr.treatment(4)
>  2 3 4
> 1 0 0 0
> 2 1 0 0
> 3 0 1 0
> 4 0 0 1
> 
> However, when I try to create a model matrix using contr.identity specified
> in options(), it actually uses the contr.treatment option. Why is that? Any
> hint on how can I do this?


It's not actually using contr.treatment, it's just calling contr.identity with contrasts=TRUE...

I don't think there's a painless way to avoid this. The closest I can think of is

cI <- contr.treatment
formals(cI)$contrasts <- FALSE
dd <- data.frame(a = gl(3,4), b = gl(4,1,12))
model.matrix(~ C(a,cI,3) + C(b,cI,4), dd)



-- 
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list