在 R model.matrix 中专门指定对比
Specifically assign contrasts in R model.matrix
如果我有一个 2 级的变量(条件)并想创建一个 model.matrix 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)
您可以使用 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"
如果我有一个 2 级的变量(条件)并想创建一个 model.matrix 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)
您可以使用 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"