在R中整合曲线下的部分区域

时间:2015-03-20 18:31:27

标签: r partial auc

我将高斯曲线拟合到下面的数据,并且我想计算某些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)

2 个答案:

答案 0 :(得分:0)

假设您的数据位于变量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)

the plot resulting from your data

答案 1 :(得分: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