使用 model.matrix() 创建虚拟变量
Using model.matrix() to create dummy variables
以下代码无效,有人可以提供帮助吗?
dataframe1<-data.frame(x1 = c(1:5) , x2 = 1 , x3 = 0)
dataframe1
model.matrix(~x1 - 1 , dataframe1)
将x1
作为因子变量。
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"
我们也可以转换为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
以下代码无效,有人可以提供帮助吗?
dataframe1<-data.frame(x1 = c(1:5) , x2 = 1 , x3 = 0)
dataframe1
model.matrix(~x1 - 1 , dataframe1)
将x1
作为因子变量。
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"
我们也可以转换为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