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: regress.loglog

Function Description: regress.loglog

Performs regression and graphs in a convenient way: with or without log-transforming x and y variables (the option addone can be included to handle zeros for log-transformation), with or without manual point labelling, without or without the best-fit line added, and with many options for colors and points. add can be a vector of length 2, a constant to be added to every value of x, y to remove zeroes.

Function Arguments:

ArgumentDefault Value
x
y
xlogTRUE
ylogTRUE
addoneNULL
graphitTRUE
xrangeNULL
yrangeNULL
addFALSE
pts16
lwidth1
drawli"solid"
title""
xtitleNULL
ytitleNULL
ptnamesNULL
ptsize1
clr"blue"
lineclr"red"
includeaxisTRUE

Function Source:


regress.loglog=function(x,y,xlog=TRUE,ylog=TRUE,addone=NULL,graphit=TRUE,xrange=NULL,yrange=NULL,add
        =FALSE,pts=16,lwidth=1,
drawline="solid",title="",xtitle=NULL,ytitle=NULL,ptnames=NULL,ptsize=1,clr=
        "blue",lineclr="red",includeaxis=TRUE) {
exist = !is.na(x) & !is.na(y)
x=x[exist]
y=y[exist]
ptnames=ptnames[exist]

if(!is.null(addone))
{
x[x==0]=x[x==0]+addone[1]
y[y==0]=y[y==0]+addone[2]
}

pos = !is.na(x)
if(xlog) pos = pos & x>0
if(ylog) pos = pos & y>0
x=x[pos]

if(length(x)==0) return(list(coef=NULL,prob=NULL,rsq=NULL,pred=NULL,full=NULL)) ## Added March 20
        10
y=y[pos]
ptnames=ptnames[pos]

if(xlog) xreg=log(x)
else xreg=x
if(ylog) yreg=log(y)
else yreg=y

fit=lm(yreg~xreg)

regcoef=summary(fit)$coef[,1]
prob=summary(fit)$coef[,4]
rsq=cor(xreg,yreg)^2

if(is.null(xrange)) xrange=range(x)
if(is.null(yrange)) yrange=range(y)
if(is.null(xtitle)) xtitle="x"
if(is.null(ytitle)) ytitle="y"

if(ylog) predy=exp(fit$fitted)
else predy=fit$fitted

if(graphit)
{
logaxs=""
if(xlog) logaxs=pst(logaxs,"x")
if(ylog) logaxs=pst(logaxs,"y")

if(add & !is.null(pts)) points(x,y,pch=pts,col=clr,cex=ptsize,cex.lab=ptsize,cex.axis=ptsize)

if(!add & !is.null(pts))

plot(x,y,pch=pts,main=title,log=logaxs,xlim=xrange,ylim=yrange,xlab=xtitle,ylab=ytitle,col=clr
        , cex=ptsize,cex.lab=ptsize,cex.axis=ptsize,axes=includeaxis)
if(!includeaxis) box()

ord=order(x)
if(!is.null(drawline)) lines(x[ord],predy[ord],col=lineclr,lty=drawline,lwd=lwidth)

if(!is.null(ptnames)) identify(x,y,ptnames)
}

return(list(coef=regcoef,prob=prob,rsq=rsq,pred=predy,full=summary(fit)))
}