问题描述
这个函数的参数R是一个常数,值为22.5。我想使用非线性回归(nls()
函数)来估计参数 A 和 B。我做了几次尝试,但都没有成功。我对 R 中的这种类型的操作不是很熟悉,所以我想得到你的帮助。
此外,如果可能,我还想使用 ggplot2
绘制此函数。
# Initial data
x <- c(0,60,90,120,180,240)
y <- c(0,0.967676,1.290101,1.327099,1.272404,1.354246)
R <- 22.5
df <- data.frame(x,y)
f <- function(x) (1/(n^2))*exp((-B*(n^2)*(pi^2)*x)/(R^2))
# First try
nls(formula = y ~ A*(1-(6/(pi^2))*sum(f,seq(1,Inf,1))),data = df,start = list(A = 1,B = 0.7))
Error in seq.default(1,1) : 'to' must be a finite number
# Second try
nls(formula = y ~ A*(1-(6/(pi^2))*integrate(f,1,Inf)),B = 0.7))
Error in f(x,...) : object 'n' not found
解决方法
您可以使用有限和近似值。使用 25 个术语:
f <- function(x,B,n = 1:25) sum((1/(n^2))*exp((-B*(n^2)*(pi^2)*x)/(R^2)))
fm <- nls(formula = y ~ cbind(A = (1-(6/pi^2))* Vectorize(f)(x,B)),data = df,start = list(B = 0.7),alg = "plinear")
fm
给予:
Nonlinear regression model
model: y ~ cbind(A = (1 - (6/pi^2)) * Vectorize(f)(x,B))
data: df
B .lin.A
-0.00169 1.39214
residual sum-of-squares: 1.054
Number of iterations to convergence: 12
Achieved convergence tolerance: 9.314e-06
模型似乎不太适合数据(下图中的实线);然而,逻辑模型似乎运行良好(虚线)。
fm2 <- nls(y ~ SSlogis(x,Asym,xmid,scal),df)
plot(y ~ x,df)
lines(fitted(fm) ~ x,df)
lines(fitted(fm2) ~ x,df,lty = 2)
legend("bottomright",c("fm","fm2"),lty = 1:2)