2

the following code doesn't work, could someone offer help?

dataframe1<-data.frame(x1 = c(1:5) , x2 = 1 , x3 = 0)
dataframe1
model.matrix(~x1 - 1 , dataframe1)
Mathilda Fang
  • 353
  • 1
  • 13

2 Answers2

2

We could also convert to character

dataframe1$x1 <-  as.character(dataframe1$x1)
> model.matrix(~x1 - 1, dataframe1)
  x11 x12 x13 x14 x15
1   1   0   0   0   0
2   0   1   0   0   0
3   0   0   1   0   0
4   0   0   0   1   0
5   0   0   0   0   1
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Make x1 as factor variable.

dataframe1<-data.frame(x1 = c(1:5) , x2 = 1 , x3 = 0)
dataframe1$x1 <- factor(dataframe1$x1)
model.matrix(~x1 - 1, dataframe1)

#  x11 x12 x13 x14 x15
#1   1   0   0   0   0
#2   0   1   0   0   0
#3   0   0   1   0   0
#4   0   0   0   1   0
#5   0   0   0   0   1
#attr(,"assign")
#[1] 1 1 1 1 1
#attr(,"contrasts")
#attr(,"contrasts")$x1
#[1] "contr.treatment"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213