[R] Design matrix not identity
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Wed May 12 18:37:11 CEST 2004
Patrik Waldmann <Patrik.Waldmann at genfys.slu.se> writes:
> Hello again,
>
> I was too quick before. What I was looking for was a function that
> constructs the design (or incidence) matrix (X in a linear model) from a
> factor. Uwe Ligges suggested using model.matrix and this does almost what I
> want, but it is first necessary to construct a data variable. It also asigns
> ones to all rows of the first column (because this is set to be the
> contrast, not really what I want - see below). Maybe time for a function
> that just converts a factor into a design matrix?
>
> I have a factor
> factor<-as.factor(c(1,1,2,2,3,3,3))
That could get you in trouble by masking the factor() function...
> and I want a matrix
> 1 0 0
> 1 0 0
> 0 1 0
> 0 1 0
> 0 0 1
> 0 0 1
> 0 0 1
f <- factor(c(1,1,2,2,3,3,3))
model.matrix(~f-1)
Or, a different approach:
diag(3)[f,]
--
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