在这种情况下如何理解 rep() 的用法?

How to understand the usage of rep() in this case?

有一个数据集randomdat包含299个obs,两个分类变量,var 9包含像With XYZWithout XYZ这样的值,var8包含像这样的值Group A/Group B/Group C,var1为数值变量。

然后是模型:

m7 <- lm(var3~var1+I(var1^2)+I(var1^3)+var9, data=randomdat)

检查summary(m7),显示Without XYZ总是比With XYZ.

小34451.4
> summary(m7)

Call:
lm(formula = var3 ~ var1 + I(var1^2) + I(var1^3) + var9, data = randomdat)

Residuals:
    Min      1Q  Median      3Q     Max 
-391506  -75127    4799   77175  323856 

Coefficients:
                     Estimate    Std. Error t value            Pr(>|t|)    
(Intercept)     -162934.42035   18571.30251  -8.773 <0.0000000000000002 ***
var1              10927.87454     741.36511  14.740 <0.0000000000000002 ***
I(var1^2)          -180.82979      10.44006 -17.321 <0.0000000000000002 ***
I(var1^3)             0.99499       0.04223  23.562 <0.0000000000000002 ***
var9Without XYZ  -34451.43378   14570.55030  -2.364              0.0187 *  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 117500 on 294 degrees of freedom
Multiple R-squared:  0.8642,    Adjusted R-squared:  0.8624 
F-statistic: 467.9 on 4 and 294 DF,  p-value: < 0.00000000000000022

然后有两个预测模型:

m7_predictwith <- predict(m7,list(var1=randomdat$var1, var9 = rep("With XYZ",299)))
m7_predictwout <- predict(m7,list(var1=randomdat$var1, var9 = rep("Without XYZ",299)))

如果绘制它们,您会看到两条线不重叠。

ggplot(randomdat, aes(x = var1, y = var3)) + 
    geom_point(aes(colour = var8, shape = var8)) + 
    geom_line(aes(x=randomdat$var1,y=m7_predictwith), color = 'red', lty = 2) + 
    geom_line(aes(x=randomdat$var1,y=m7_predictwout), color = 'black', lty = 3)

现在问题来了,在这种情况下如何理解var9 = rep("With XYZ",299)var9 = rep("Without XYZ",299)?不是说把var9里面的值全部替换成With XYZ或者Without XYZ吗? var1m7_predictwithm7_predictwout中是一样的,它们的剧情线应该是同一条线吧?在这种情况下,对 rep() 的语法用法非常困惑。

rep() 重复值:

> rep("With XYZ", 5)
[1] "With XYZ" "With XYZ" "With XYZ" "With XYZ" "With XYZ"

此处用于创建包含以下内容的数据集:

  • 观察值var1
  • var9的固定值。

var9是一个因子变量,在回归中它的估计系数是-34451.43378。因此,如果您预测一条线的 var9 的固定值为 "With XYZ",然后预测另一条线的固定值为 "Without XYZ",则 "Without XYZ" 线将向下移动常数值 34451,创建平行线。