是否存在一个原生R函数,它将获取一个输入向量并返回相应的二进制矩阵,其中矩阵的列数与输入向量中的唯一值相同?
例如,给定x <- 1:3
,我想返回以下矩阵:
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
函数contrasts
接近,但我似乎无法绕过返回的n-1列:
> contrasts(as.factor(x))
2 3
1 0 0
2 1 0
3 0 1
答案 0 :(得分:5)
model.matrix()
可能会有所帮助,但你需要抑制拦截:
> model.matrix(~ factor(1:3) - 1)
factor(1:3)1 factor(1:3)2 factor(1:3)3
1 1 0 0
2 0 1 0
3 0 0 1
attr(,"assign")
[1] 1 1 1
attr(,"contrasts")
attr(,"contrasts")$`factor(1:3)`
[1] "contr.treatment"
稍微复杂一些:
> set.seed(1)
> fac <- factor(sample(1:3, 10, replace = TRUE))
> model.matrix(~ fac - 1)
fac1 fac2 fac3
1 1 0 0
2 0 1 0
3 0 1 0
4 0 0 1
5 1 0 0
6 0 0 1
7 0 0 1
8 0 1 0
9 0 1 0
10 1 0 0
attr(,"assign")
[1] 1 1 1
attr(,"contrasts")
attr(,"contrasts")$fac
[1] "contr.treatment"
答案 1 :(得分:5)
实际上,contrasts
就是你想要的。
contrasts(as.factor(1:3), contrasts=FALSE)
1 2 3
1 1 0 0
2 0 1 0
3 0 0 1