我想在R中为因子实验创建一个无约束的设计矩阵,下面的代码给出了我想要的矩阵。但是代码需要针对每个因素以及拦截术语单独的model.matrix
命令。我很好奇是否可以通过单个衬垫获得相同的结果。感谢
y <- c(55, 56, 57, 53, 54, 55, 51, 52, 53, 61, 62, 63)
N <- gl(n = 2, k = 6, length = 2 * 6
, labels = c("Low", "High")
, ordered = FALSE)
P <- gl(n = 2, k = 3, length = 2 * 6
, labels = c("Low", "High")
, ordered = FALSE)
Data <- data.frame(y, N, P)
X <-
cbind(
model.matrix(object = y ~ 1, data = Data)
, model.matrix(object = y ~ -1 + N, data = Data)
, model.matrix(object = y ~ -1 + P, data = Data)
, model.matrix(object = y ~ -1 + N:P, data = Data)
)
print(x = X)
答案 0 :(得分:3)
不是一个班轮,但可能有点简单:
contrasts(N, nlevels(N)) <- diag(nlevels(N))
contrasts(P, nlevels(P)) <- diag(nlevels(P))
Data2 <- data.frame(y, N, P)
X2 <- model.matrix(y ~ 1 + N + P + N:P, data=Data2)
答案 1 :(得分:3)
我认为关键是将所有对比设置为FALSE。我觉得从技术上来说这可能只是一个单行......它只是一条很长的路线。
model.matrix(y ~ N +P + N:P, data=Data,
contrasts.arg = lapply(Data[,sapply(Data, is.factor)],
contrasts, contrasts=FALSE))
(Intercept) NLow NHigh PLow PHigh NLow:PLow NHigh:PLow NLow:PHigh NHigh:PHigh
1 1 1 0 1 0 1 0 0 0
2 1 1 0 1 0 1 0 0 0
3 1 1 0 1 0 1 0 0 0
4 1 1 0 0 1 0 0 1 0
5 1 1 0 0 1 0 0 1 0
6 1 1 0 0 1 0 0 1 0
7 1 0 1 1 0 0 1 0 0
8 1 0 1 1 0 0 1 0 0
9 1 0 1 1 0 0 1 0 0
10 1 0 1 0 1 0 0 0 1
11 1 0 1 0 1 0 0 0 1
12 1 0 1 0 1 0 0 0 1
attr(,"assign")
[1] 0 1 1 2 2 3 3 3 3
attr(,"contrasts")
attr(,"contrasts")$N
Low High
Low 1 0
High 0 1
attr(,"contrasts")$P
Low High
Low 1 0
High 0 1