在 R model.matrix 中专门分配对比度



如果我有一个 2 个级别的变量(条件(并且想要创建一个 model.matrix R 会自动将条件 B指定为设计矩阵中的项。

condition <- as.factor( c("A","A","A","B","B","B"))
df <- data.frame(condition)
design <- model.matrix( ~ condition)
> df
condition
1         A
2         A
3         A
4         B
5         B
6         B

> design
(Intercept) conditionB
1           1          0
2           1          0
3           1          0
4           1          1
5           1          1
6           1          1
attr(,"assign")
[1] 0 1
attr(,"contrasts")
attr(,"contrasts")$condition
[1] "contr.treatment"

问题:我想得到与条件 A相关的结果。如何在 model.matrix(( 中指定它?

(解决方法是反转生成的 FC(

您可以使用C函数来确定要考虑的基数:

以A为基数:

model.matrix(~C(condition,base=1))
(Intercept) C(condition, base = 1)2
1           1                       0
2           1                       0
3           1                       0
4           1                       1
5           1                       1
6           1                       1
attr(,"assign")
[1] 0 1
attr(,"contrasts")
attr(,"contrasts")$`C(condition, base = 1)`
2
A 0
B 1

以B为基数:

model.matrix(~C(condition,base=2))
(Intercept) C(condition, base = 2)1
1           1                       1
2           1                       1
3           1                       1
4           1                       0
5           1                       0
6           1                       0
attr(,"assign")
[1] 0 1
attr(,"contrasts")
attr(,"contrasts")$`C(condition, base = 2)`
1
A 1
B 0

这是你想要的结果吗?

df <- data.frame(condition)
design <- model.matrix( ~ condition-1)
design
conditionA conditionB
1          1          0
2          1          0
3          1          0
4          0          1
5          0          1
6          0          1
attr(,"assign")
[1] 1 1
attr(,"contrasts")
attr(,"contrasts")$`condition`
[1] "contr.treatment"

最新更新