Topic: Utilities
Topic Description:
Basic R utilities used in many packages and functions, such as date and string manipulations, statistical distributions, geometry of lines and distances. The R package date is required for the two data functions.
File: utilities/statistics.r
| View File Source | Download File | No help file available |
Function: regsum
Function Description: regsum
This carries out either first or second order polynomial regression, finds the x- and y-values at y's peak if its second order, otherwise the x-intercept.Function Arguments:
| Argument | Default Value |
|---|---|
| x | |
| y | |
| poly | 1 |
| graphit | F |
| yrange | c(-1,-1) |
| yaxslab | "multiplier" |
| newgraph | F |
| add | F |
| pts | T |
| ptype | 16 |
| ltype | "solid" |
Function Source:
regsum=function(x,y,poly=1,graphit=F,yrange=c(-1,-1),yaxslab="multiplier",
newgraph=F,add=F,pts=T,ptype=16,ltype="solid")
{
x2=x^2
x3=x^3
if(poly==1) fit=lm(y~x)
else if(poly==2) fit=lm(y~x+x2)
else if(poly==3) fit=lm(y~x+x2+x3)
a=summary(fit)$coef[1,1]
b=summary(fit)$coef[2,1]
c=d=0
if(poly>1) c=summary(fit)$coef[3,1]
if(poly>2) d=summary(fit)$coef[4,1]
pred=a+b*x+c*x2+d*x3
if(graphit)
{
if(yrange[2]<0) yrange=c(1,max(y))
if(newgraph) win.graph(height=4,width=6)
if(add)
{
if(pts) points(x-31,y,pch=ptype)
lines(x-31,pred,lty=ltype)
}
else
{
if(pts)
{
plot(x-31,y,pch=ptype,ylim=yrange,xlab="date",ylab=yaxslab)
lines(x-31,pred,lty=ltype)
}
else plot(x-31,pred,pch=ptype,ylim=yrange,xlab="date",ylab=yaxslab,type="l",lty=ltype)
}
}
if(poly==1)
{
peakday=(-a/b)
peak=NA
}
else if(poly==2)
{
peakday=(-b/(2*c))
peak=a-b^2/(4*c)
}
return(list(pred=pred,peak=peak,peakday=peakday))
}
newgraph=F,add=F,pts=T,ptype=16,ltype="solid")
{
x2=x^2
x3=x^3
if(poly==1) fit=lm(y~x)
else if(poly==2) fit=lm(y~x+x2)
else if(poly==3) fit=lm(y~x+x2+x3)
a=summary(fit)$coef[1,1]
b=summary(fit)$coef[2,1]
c=d=0
if(poly>1) c=summary(fit)$coef[3,1]
if(poly>2) d=summary(fit)$coef[4,1]
pred=a+b*x+c*x2+d*x3
if(graphit)
{
if(yrange[2]<0) yrange=c(1,max(y))
if(newgraph) win.graph(height=4,width=6)
if(add)
{
if(pts) points(x-31,y,pch=ptype)
lines(x-31,pred,lty=ltype)
}
else
{
if(pts)
{
plot(x-31,y,pch=ptype,ylim=yrange,xlab="date",ylab=yaxslab)
lines(x-31,pred,lty=ltype)
}
else plot(x-31,pred,pch=ptype,ylim=yrange,xlab="date",ylab=yaxslab,type="l",lty=ltype)
}
}
if(poly==1)
{
peakday=(-a/b)
peak=NA
}
else if(poly==2)
{
peakday=(-b/(2*c))
peak=a-b^2/(4*c)
}
return(list(pred=pred,peak=peak,peakday=peakday))
}