简体   繁体   English

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

[英]Specifically assign contrasts in R model.matrix

If I have a variable (condition) of 2 levels and want to create a model.matrix R automatically assigns conditionB as the term in the design 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"

Question : I would like to have my results relative to conditionA . 问题 :我希望得到与conditionA相关的结果。 How can I specify this in model.matrix() ? 如何在model.matrix()中指定呢?

(A workaround would be to inverse the resulting FCs) (一种解决方法是将生成的FC求逆)

You can use the C function to determine the base that you want to be taken into consideration: 您可以使用C函数来确定要考虑的基数:

Taking A as the base: 以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

Taking B as the base: 以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

Is it the result you want? 是您想要的结果吗?

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM