#creat chart
thickness<-matrix(c(14.037,14.165,13.972,13.907,14.821,14.757,14.843,14.878,13.880,13.860,14.032,13.914,14.888,14.921,14.415,14.932),byrow = T,ncol = 4)
dimnames(thickness)<- list(c("(1)","a","b","ab"),c("Rep1","Rep2","Rep3","Rep4"))
A<- rep(c(-1,1),2)
B<- c(rep(-1,2),rep(1,2))
AB <- A*B
Total<- apply(thickness,1,sum)
Average<- apply(thickness,1,mean)
Variance<- apply(thickness,1,var)
table<-cbind(A,B,AB,thickness,Total,Average,Variance)
table
#Effect estimate(1)
n<-4
Aeff <-(Total %*% A)/(2*n)
Aeff
Beff <-(Total %*% B)/(2*n)
Beff
ABeff <-(Total %*% AB)/(2*n)
ABeff
#Effect estimate(2)
n<-4
Aeff<-{sum(Total[A==+1])/(2*n)}-{sum(Total[A==-1])/(2*n)}
Aeff
Beff<-{sum(Total[B==+1])/(2*n)}-{sum(Total[B==-1])/(2*n)}
Beff
ABeff<-{sum(Total[AB==+1])/(2*n)}-{sum(Total[AB==-1])/(2*n)}
ABeff
#summary
thickness.vec<- c(t(thickness))
XA <- rep(as.factor(A),rep(2,4))
XB <- rep(as.factor(B),rep(2,4))
XAB <- rep(as.factor(AB),rep(2,4))
options(contrasts=c("contr.sum","contr.poly"))
thickness.lm<- lm(thickness.vec ~ XA+XB+XAB)
model.frame.default中的错误(公式= thickness.vec~XA + XB + XAB, :变量长度不同(找到&#39; XA&#39;)
这是r。中的因子设计
由于回归量和响应的长度不同,我无法让lm
工作。
length(thickness.vec)
#[1] 16
length(XA)
#[1] 8
length(XB)
#[1] 8
length(XAB)
#[1] 8
我不知道如何解决它 我该怎么做才能解决这个问题?
答案 0 :(得分:0)
也许你想要的是将宽格式转换为长格式。我认为手动操作并不是一个好主意。
以下是我的例子:
# install.packages("tidyverse")
library(tidyverse)
d1 <- table %>%
as.tibble() %>% # transform into tbl_df to manipulate easily
select(A, B, AB, Rep1, Rep2, Rep3, Rep4) %>% # select interested cols
gather(key = "Rep", value = "thickness", -A, -B, -AB) %>% # change into longformat
mutate(A = as.factor(A), B = as.factor(B), AB = as.factor(AB)) # change classes
options(contrasts=c("contr.sum","contr.poly"))
thickness.lm <- lm(thickness ~ A + B + AB, data = d1)
summary(thickness.lm)
[编辑(更新)]
lm()
使用带有data.frame的公式,在一行中想要一个因变量和一组自变量。
但是你的表,每行有四个因变量。所以我把你的桌子变成了长格式
-term
未收集但重复(请参阅help(gather, tidyr)
)
在R中,字母顺序是因子级别的默认顺序,它会影响输出的外观。
d2 <- table %>%
as.tibble() %>%
select(A, B, AB, Rep1, Rep2, Rep3, Rep4) %>%
gather(key = "Rep", value = "thickness", -A, -B, -AB) %>%
mutate(A = factor(A, levels = c(1, -1)), # change class with definition of levels' order.
B =factor(B, levels = c(1, -1)),
AB = factor(AB, levels = c(1, -1)))
> d1$A
[1] -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1
Levels: -1 1
> d2$A
[1] -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1
Levels: 1 -1
options(contrasts=c("contr.sum","contr.poly"))
thickness.lm2 <- lm(thickness ~ A + B + AB, data = d2)
summary(thickness.lm2)
# AB is an interaction term, isn't it? if so, you needn't prepare the value.
thickness.lm3 <- lm(thickness ~ A * B, data = d2)
summary(thickness.lm3)