关键是后面提示的错误要解决。
是的。每次使用程序包都必须首先加载。比如:library(rootSolve)
library(tm)
在R中加载包是非常容易的,有两个函数可以做到:library 和 require。他们之间有一些细微的差别,主要的区别在于 require 会返回一个布尔值(True或False)来表示被加载的包是不是可用,而 library 函数会根据调用方式不同而有不同返回结果(这点在本书不重要)。要加载这些包可以用library或require任意一种。
nls的数据源必须有误差。不能精确等于公式返回值(零残差)。循环次数大于50通常是使用 函数精确返回值 作为数据源去拟合函数。必须给y值加上随机误差。
z=function(x,a,b){a*sin(x)+b*cos(x)}x=seq(1,10,9/500)
y=z(x,1,1) # a=1 b=1 是期望拟合出的结果。
cor=data.frame(x=x,y=y)
cor$res=runif(length(cor$x),min=-0.005,max=0.005)
cor$yres=cor$y+cor$res
#yres =y加上随机误差,y是精确返回值
> nls(cor$yres~z(cor$x,a,b),data=cor,start=list(a=0.8,b=1.3))
Nonlinear regression model
model: cor$yres ~ z(cor$x, a, b)
data: cor
a b
0.9999 1.0002
residual sum-of-squares: 0.004213
Number of iterations to convergence: 1
Achieved convergence tolerance: 2.554e-07
#使用精确返回值拟合就会出错。
> nls(cor$y~z(cor$x,a,b),data=cor,start=list(a=1,b=1))
Error in nls(cor$y ~ z(cor$x, a, b), data = cor, start = list(a = 1, b = 1)) :
循环次数超过了50这个最大值