在R模型中专门分配对比度

时间:2018-07-03 09:33:29

标签: r model.matrix

如果我有2个级别的变量(条件)并想要创建模型,矩阵R会在设计矩阵中自动将 conditionB 分配为该术语。

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"

问题:我希望获得与 conditionA 相关的结果。如何在model.matrix()中指定呢?

(一种解决方法是将产生的FC求逆)

2 个答案:

答案 0 :(得分:0)

您可以使用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

答案 1 :(得分: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"