[R] Design matrix not identity
Prof Brian Ripley
ripley at stats.ox.ac.uk
Wed May 12 18:47:02 CEST 2004
On Wed, 12 May 2004, Patrik Waldmann wrote:
> 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.
Eh? You have to construct the factor, and nothing else.
> 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?
Uwe was quite correct, and you were still too quick.
[Don't call an object after an R function. Let's use a sensible name like
`f'.]
f <- as.factor(c(1,1,2,2,3,3,3))
model.matrix(~ 0 + f)
or
diag(nlevels(f))[f,]
gives what you illustrate.
> I have a factor
> factor<-as.factor(c(1,1,2,2,3,3,3))
>
> 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
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
PLEASE do.
--
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