1

我已经将高斯曲线拟合到以下数据,并且我想计算某些 x 值之间的曲线下面积(例如,从 x=6 到 x=18)。以下代码产生以下错误:“f(x, c(m, s, a, b)) 中的错误:未使用的参数 (c(m, s, a, b))”。另外,我有一些负值,需要从正值中减去负值区域,因为我对“净”值感兴趣。

x <- c(12.88, 12.9, 8.35, 10.52, 10.45, 8.44, 9.01, 9.96, 9.82, 9.83, 10.65, 10.69, 15.3, 15.33, 12.41, 12.43, 8.36, 8.43, 9.29, 9.25, 14.78, 14.87, 16.17, 16.23, 3.59, 4.37, 3.88, 19.88, 20.71, 20.33, 21.25, 22.09)
y<-c(10.8, 9.62, 11.76, 5.12, 9.63, 4.80, 11.09, 7.42, 7.79, 9.76, 9.71, 8.13, 14.4, 14.85, 12.84, 11.59, 7.0, 6.49, 5.94, 4.93, 6.43, 7.8, 3.81, 2.6, -0.93, 5.3, 1.08, 0.39, -0.59, 2.77, 3.5, -2.08)
df<-data.frame(x, y)

#Define a Gaussian function (Y=Amplitude*exp(-0.5*((X-Mean)/SD)^2) + Baseline)
f<-function(x, theta) {
   m<-theta[1]; s<-theta[2]; a<-theta[3]; b<-theta[4];
   a*exp(-0.5*((x-m)/s)^2) + b
}

fit<-nls(y~f(x,c(m,s,a,b)), data.frame(x,y), start=list(m=12, s=5, a=12,  b=-2)) 
xs<-seq(0,24,l=1000)
f<-function(x) predict(fit,newdata=data.frame(x=xs))
integrate(f,6,18)
4

2 回答 2

1

假设您的数据在变量中TimeOfDayy这应该有效(我假设黄土曲线将满足您的需求。您可能(将)需要根据您的数据更改您正在拟合的模型。根据模型,您的被积函数会改变你的结果也会如此!!)

df <- data.frame(TimeOfDay,y)
df <- df[order(df$TimeOfDay),]
l <- loess(y ~ TimeOfDay, df, control=loess.control(surface="direct"))
f <- function(x) predict(l,newdata = x)

integrate(f,2,3) #you can specify between what times you want to integrate here

plot(df)
lines(l)

从您的数据得出的图

于 2015-03-20T20:21:12.033 回答
0
> fit
Nonlinear regression model
  model: y ~ f(x, c(m, s, a, b))
   data: data.frame(x, y)
     m      s      a      b 
12.423  4.922 11.949 -1.696 
 residual sum-of-squares: 244.6

Number of iterations to convergence: 11 
Achieved convergence tolerance: 7.947e-06
#---------------------------------
 integrate(function(x){
       11.949*exp(-0.5*((x-12.423)/4.922)^2) -1.696}
       ,6,18)
# 93.96736 with absolute error < 1e-12
于 2015-03-20T23:03:03.913 回答