R - 将列名称作为变量传递,名称包含 I()

R - Pass column names as Variable with names contain I()

我正在执行多项式回归并测试系数的线性组合。但是我 运行 在尝试测试系数的线性组合时遇到了一些问题。

LnModel_1 <- lm(formula = PROF ~ UI_1+UI_2+I(UI_1^2)+UI_1:UI_2+I(UI_2^2)) 
summary(LnModel_1)

它输出以下值:

Call:
lm(formula = PROF ~ UI_1 + UI_2 + I(UI_1^2) + UI_1:UI_2 + I(UI_2^2))
Residuals:
 Min      1Q  Median      3Q     Max 
-3.4492 -0.5405  0.1096  0.4226  1.7346 
Coefficients:
Estimate Std. Error t value Pr(>|t|)    
(Intercept)  4.66274    0.06444  72.354  < 2e-16 ***
UI_1         0.25665    0.07009   3.662 0.000278 ***
UI_2         0.25569    0.09221   2.773 0.005775 ** 
I(UI_1^2)   -0.15168    0.04490  -3.378 0.000789 ***
I(UI_2^2)   -0.08418    0.05162  -1.631 0.103643    
UI_1:UI_2   -0.02849    0.05453  -0.522 0.601621

然后我使用 names(coef()) 提取系数名称

names(coef(LnModel_1))
output:
[1] "(Intercept)" "UI_1"        "UI_2"        "I(UI_1^2)" 
"I(UI_2^2)""UI_1:UI_2" 

由于某些原因,当我使用 glht() 时,它在 UI_2^2

上给我一个错误
slope <- glht(LnModel_1, linfct = c("UI_2+ UI_1:UI_2*2.5+ 2*2.5*I(UI_2^2) =0
") )
Output:
Error: multcomp:::expression2coef::walkCode::eval: within ‘UI_2^2’, the term
‘UI_2’ must not denote an effect. Apart from that, the term must evaluate to
a real valued constant

不知道为什么会给我这个错误信息。如何将 I(UI_2^2) 系数输入到 glht()

非常感谢

问题似乎是 I(UI^2) 可以按照您在此处所做的相同方式解释为 R 中的表达式 LnModel_1 <- lm(formula = PROF ~ UI_1+UI_2+I(UI_1^2)+UI_1:UI_2+I(UI_2^2))

因此,您应该指明 R 您想要计算字符串中的 string

slope <- glht(LnModel_1, linfct = c("UI_2+ UI_1:UI_2*2.5+ 2*2.5*\`I(UI_2^2)\` =0
") )

检查我的示例(因为我无法重现您的问题):

library(multcomp)

cars <- copy(mtcars)
setnames(cars, "disp", "UI_2")
model <- lm(mpg~I(UI_2^2),cars)

names(coef(model))

slope <- glht(model, linfct = c("2*2.5*\`I(UI_2^2)\` =0") )