R';s lm在有序因子下表现出奇怪的行为

R';s lm在有序因子下表现出奇怪的行为,r,lm,R,Lm,当我在lm函数中插入有序因子时,结果(对我来说)是意外的 这当然有一个很好的解释 # Generate some data # parameters n = 20L set.seed(11L) # Ordered factor t <- factor(sample(c(1L, 2L), size = n, replace = TRUE), label = c("Low", "High"), ordered = TRUE) t [1] Low Low H

当我在
lm
函数中插入有序因子时,结果(对我来说)是意外的

这当然有一个很好的解释

# Generate some data
# parameters
n = 20L
set.seed(11L)

# Ordered factor
t <- factor(sample(c(1L, 2L), size = n, replace = TRUE),
       label = c("Low", "High"), 
       ordered = TRUE)
t
 [1] Low  Low  High Low  Low  High Low  Low  High Low  Low  Low  High
[14] High High High Low  Low  Low  Low 
Levels: Low < High

# not ordered factor, keep reference level as High
tno <- factor(t , ordered = FALSE)
tno <- relevel(tno, ref = "High")
tno
 [1] Low  Low  High Low  Low  High Low  Low  High Low  Low  Low  High
[14] High High High Low  Low  Low  Low 
Levels: High Low

# A simple indicator variable
ti <- t == "Low"
ti
 [1]  TRUE  TRUE FALSE  TRUE  TRUE FALSE  TRUE  TRUE FALSE  TRUE  TRUE
[12]  TRUE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE

# Some dependent variable
y <- 10*rnorm(n)

# Run three regression
# Observe ordered factor is not giving the correct results
lm(y ~ t)
Call:
lm(formula = y ~ t)

Coefficients:
(Intercept)          t.L  
    -3.6082       0.8038

lm(y ~ tno)
Call:
lm(formula = y ~ tno)

Coefficients:
(Intercept)       tnoLow  
     -3.040       -1.137 

lm(y ~ ti)
Call:
lm(formula = y ~ ti)

Coefficients:
(Intercept)       tiTRUE  
     -3.040       -1.137  


# Confirm correct intercept
mean(y[t == "High"])
[1] -3.039771
# Just rounding difference...
#生成一些数据
#参数
n=20L
结实种子(11升)
#有序因子
t试着运行这个

rest<- lm(y ~ t)
restno <- lm(y ~ tno)
resti <- lm(y ~ ti)

rest$fitted.values
restno$fitted.values
resti$fitted.values

rest$xlevels
restno$xlevels
resti$xlevels

rest$contrasts
restno$contrasts
resti$contrasts
同样地

rest_treatment<- lm(y ~ t, contrasts = list(t = "contr.treatment"))
rest\u治疗尝试运行此

rest<- lm(y ~ t)
restno <- lm(y ~ tno)
resti <- lm(y ~ ti)

rest$fitted.values
restno$fitted.values
resti$fitted.values

rest$xlevels
restno$xlevels
resti$xlevels

rest$contrasts
restno$contrasts
resti$contrasts
同样地

rest_treatment<- lm(y ~ t, contrasts = list(t = "contr.treatment"))
rest\u治疗