How to create design matrix in r -
i have 2 factors. factor have 2 level, factor b have 3 level.
how create following design matrix?
factora1 factora2 factorb1 factorb2 factorb3 [1,] 1 0 1 0 0 [2,] 1 0 0 1 0 [3,] 1 0 0 0 1 [4,] 0 1 1 0 0 [5,] 0 1 0 1 0 [6,] 0 1 0 0 1
you have couple of options:
use base , piece yourself:
(iris.dummy<-with(iris,model.matrix(~species-1))) (iris<-data.frame(iris,iris.dummy)) or use ade4 package follows:
dummy <- function(df) { require(ade4) isfact <- sapply(df, is.factor) facts <- acm.disjonctif(df[, isfact, drop = false]) nonfacts <- df[, !isfact,drop = false] data.frame(nonfacts, facts) } dat <-data.frame(eggs = c("foo", "foo", "bar", "bar"), ham = c("red","blue","green","red"), x=rnorm(4)) dummy(dat) ## x eggs.bar eggs.foo ham.blue ham.green ham.red ## 1 0.3365302 0 1 0 0 1 ## 2 1.1341354 0 1 1 0 0 ## 3 2.0489741 1 0 0 1 0 ## 4 1.1019108 1 0 0 0 1
Comments
Post a Comment