R - 创建具有固定poly()系数的线性模型

时间:2015-06-03 08:12:19

标签: r distribution lm polynomials

在R中,可以使用公式中的lm()参数构建具有固定系数的glm()offset对象。

x=seq(1,100)
y=x^2+3*x+7
# Forcing to fit the polynomial: 2x^2 + 4x + 8 
fixed_model = lm(y ~ 0 + offset(8 + 4*x + 2*I(x^2) ))

是否可以使用poly()执行相同的操作?我尝试了下面的代码,但它似乎不起作用。

fixed_model_w_poly <- lm(y ~ 0 + offset(poly(x, order=2, raw = TRUE, coefs= c(8, 4, 2))))
  

错误:偏移量为200,应等于100(观察次数)

我想使用poly()作为方便的界面来运行具有大量固定系数或订单值的迭代,而不必为每个订单/系数组合手动编码:offset(8 + 4*x + 2*I(x^2) )

P.S:进一步但不是必要的信息:这是进入MCMC例程。因此,示例用法是在以下代码中生成(然后比较)model_currentmodel_next

library(MASS)
coeffs_current <- c(8, 4, 2)
model_current <- lm(y ~ 0 + offset(poly(x, order=2, raw = TRUE, coefs= coeffs_current )))
cov <- diag(rep(1,3))
coeffs_next <- mvrnorm(1, mu = as.numeric(coeffs_current ),
                       Sigma = cov ) 
model_next <- lm(y ~ 0 + offset(poly(x, order=2, raw = TRUE, coeffs_next ))

1 个答案:

答案 0 :(得分:1)

这证明了我的建议。 (使用poly。)

library(MASS)
# coeffs_current <- c(8, 4, 2) Name change for compactness.
cc <- c(8, 4, 2)
form <- as.formula(bquote(y~x+offset(.(cc[1])+x*.(cc[2])+.(cc[3])*I(x^2) )))
model_current <- lm(form, data=dat))

我真的不知道你打算用下一个代码做什么。看起来你想要一些基于先前函数输入的东西,但看起来不像你希望它基于结果。

cov <- diag(rep(1,3))
coeffs_next <- mvrnorm(1, mu = as.numeric(cc ),
                       Sigma = cov )

该代码使用简单的测试用例(至少按照我的意图)。 bquote函数将值替换为表达式(实际上是调用),as.formula函数计算其参数,然后将结果作为正确的formula - 对象。

dat <- data.frame(x=rnorm(20), y=rnorm(20) )
cc <- c(8, 4, 2)
form <- as.formula( bquote(y~x+offset(.(cc[1])+x*.(cc[2])+.(cc[3])*I(x^2) )))
model_current <- lm(form, data=dat)
#--------
> model_current

Call:
lm(formula = form, data = dat)

Coefficients:
(Intercept)            x  
     -9.372       -5.326    # Bizarre results due to the offset.
#--------
form
#y ~ x + offset(8 + x * 4 + 2 * I(x^2))
相关问题