n = 50
set.seed(100)
x = matrix(runif(n, -2, 2), nrow=n)
y = 2 + 0.75*sin(x) - 0.75*cos(x) + rnorm(n, 0, 0.2)
在R中,我想通过最小二乘法估算上述样条函数。
以下提示希望我生成设计矩阵:
nknots = 12
mat.tpb = function(x, nknots){
n = length(x)
knots = seq(-2, 2, len=nknots)
zb = cbind(1, x ,x^2, x^3)
zt = matrix(NA, nrow=n, ncol=nknots)
for(i in 1:nknots){zt[,i] = ifelse(x>knots[i], (x-knots[i]) ^3, 0)}
cbind(zb, zt)}
z = mat.tpb(x, nknots)
我简化了上面的内容以便于阅读:
mat.tpb = function(x, 12){
zb = cbind(1, x ,x^2, x^3)
zt = matrix(NA, nrow=length(x), ncol=12)
for(i in 1:12){zt[,i] = ifelse(x>seq(-2, 2, len=12)[i], (x-seq(-2, 2, len=12)[i])^3, 0)}
cbind(zb, zt)}
z = mat.tpb(x, 12)
我认为函数“ g_k + j + 1(x)”中的“ t_j”在提示中表示“ seq(-2,2,len = 12)”。
从那时起
> seq(-2, 2, len=12)
[1] -2.0000000 -1.6363636 -1.2727273 -0.9090909 -0.5454545 -0.1818182 0.1818182 0.5454545 0.9090909 1.2727273 1.6363636 2.0000000'
字面上是
E(y | x)=λ_1×1 +λ_2×x +λ_3×x ^ 2 +λ_4×x ^ 3 +
λ_5×max{x-(-2+(4/11)×0),0} ^ 3 +λ_6×max{(x-(-2+(4/11)×1),0 } ^ 3 +λ_7×max{(x-(-2+(4/11)×2),0} ^ 3 +λ_8×max{(x-(-2+(4/11)×3) ,0} ^ 3 +λ_9×max{(x-(-2+(4/11)×4),0} ^ 3 +λ_10×max{(x-(-2+(4/11)× 5),0} ^ 3 +λ_11×max{(x-(-2+(4/11)×6),0} ^ 3 +λ_12×max{(x-(-2+(4/11 )×7),0} ^ 3 +λ_13×max{(x-(-2+(4/11)×8),0} ^ 3 +λ_14×max{(x-(-2+(4 / 11)×9),0} ^ 3 +λ_15×max{(x-(-2+(4/11)×10),0} ^ 3 +λ_16×max{(x-(-2( 4/11)×11),0} ^ 3
字面上是
λ_1×1 +λ_2×x +λ_3×x ^ 2 +λ_4×x ^ 3 + λ_5×max {(x + 2),0} ^ 3 +λ_6×max{(x + 18/11),0} ^ 3 +λ_7×max{(x + 14/11),0} ^ 3 +λ_8×max{(x + 10/11),0} ^ 3 +λ_9×max{(x + 6/11),0} ^ 3 +λ_10×max{(x + 2/11) ,0} ^ 3 +λ_11×max{(x-2 / 11),0} ^ 3 +λ_12×max{(x-6 / 11),0} ^ 3 +λ_13×max{(x- 10/11),0} ^ 3 +λ_14×max{(x-14 / 11),0} ^ 3 +λ_15×max{(x-18 / 11),0} ^ 3 +λ_16×max {(x-2),0} ^ 3
但是我不知道为什么提示要我生成设计矩阵,
所以我只想估算一下我简化的函数。
但它会这样:
> summary(lm(y ~ x+I(x^2)+I(x^3)+I(max(x+2, 0))^3+ I(max(x+(18/11), 0))^3+ I(max(x+(14/11), 0))^3+ I(max(x+(10/11), 0))^3+ I(max(x+(6/11), 0))^3+ I(max(x+(2/11), 0))^3+ I(max(x-(2/11), 0))^3+ I(max(x-(6/11), 0))^3+ I(max(x-(10/11), 0))^3+ I(max(x-(14/11), 0))^3+ I(max(x-(18/11), 0))^3+ I(max(x-2, 0))^3))
Error in model.frame.default(formula = y ~ x + I(x^2) + I(x^3) + I(max(x + :
variable lengths differ (found for 'I(max(x + 2, 0))')
请在R中告诉我,我可以使用哪些函数或包来估算我扩展的函数,
或者您知道提示的含义,并且还有其他估算方法,请也告诉我。
非常感谢您。