Thursday, May 17, 2007

Random number generation

Luc Devroye from McGill University's School of Computer Science has provided pdf copies of his book, "Non-Uniform Random Variate Generation," on-line.

http://cg.scs.carleton.ca/~luc/rnbookindex.html

Most common distributions are already built into R, but sometimes you need to build your own -- Luc provides the algorithms to do it.

Repeat elements of a vector

Two methods. The first produces a vector, the second a one column matrix.

x=1:10

# Method 1
rep(x,each=3)

# Method 2
matrix(t(matrix(x,length(x),3)))

Convert image to matrix in R

This is how to use the Pixmap library to read in an image as a matrix.


> library(pixmap)
# the next command may only work on Linux
> system("convert foo.tiff foo.ppm")
> img <- read.pnm("foo.ppm")


To get info on your new object:

> str(img)

Although included in the previous output, the size of the image can be extracted by:

>img@size

Then to extract the red channel from the image for the first ten rows:

> myextract <- img@red[1:10,]

Or to extract the entire red channel to an actual matrix:

> red.mat<-matrix(NA,img@size[1],img@size[2])
> red.mat<-img@red

Wednesday, May 16, 2007

Calculate turning angles and step lengths from location data

anglefun <- function(xx,yy,bearing=TRUE,as.deg=FALSE){
  ## calculates the compass bearing of the line between two points
## xx and yy are the differences in x and y coordinates between two points
## Options:
## bearing = FALSE returns +/- pi instead of 0:2*pi
## as.deg = TRUE returns degrees instead of radians
c = 1
if (as.deg){
c = 180/pi
}

b<-sign(xx)
b[b==0]<-1 #corrects for the fact that sign(0) == 0
tempangle = b*(yy<0)*pi+atan(xx/yy)
if(bearing){
#return a compass bearing 0 to 2pi
#if bearing==FALSE then a heading (+/- pi) is returned
tempangle[tempangle<0]<-tempangle[tempangle<0]+2*pi
}
return(tempangle*c)
}

bearing.ta <- function(loc1,loc2,loc3,as.deg=FALSE){
## calculates the bearing and length of the two lines
## formed by three points
## the turning angle from the first bearing to the
## second bearing is also calculated
## locations are assumed to be in (X,Y) format.
## Options:
## as.deg = TRUE returns degrees instead of radians
if (length(loc1) != 2 | length(loc2) != 2 | length(loc3) !=2){
print("Locations must consist of either three vectors, length == 2,
or three two-column dataframes"
)
return(NaN)
}
c = 1
if (as.deg){
c = 180/pi
}

locdiff1<-loc2-loc1
locdiff2<-loc3-loc2
bearing1<-anglefun(locdiff1[1],locdiff1[2],bearing=F)
bearing2<-anglefun(locdiff2[1],locdiff2[2],bearing=F)

if(is.data.frame(locdiff1)){
dist1<-sqrt(rowSums(locdiff1^2))
dist2<-sqrt(rowSums(locdiff2^2))
}else{
dist1<-sqrt(sum(locdiff1^2))
dist2<-sqrt(sum(locdiff2^2))
}

ta=(bearing2-bearing1)

ta[ta < -pi] = ta[ta < -pi] + 2*pi
ta[ta > pi] = ta[ta > pi] - 2*pi
return(list(bearing1=unlist(bearing1*c),bearing2=unlist(bearing2*c),
ta=unlist(ta*c),dist1=unlist(dist1),dist2=unlist(dist2)))
}