Skip to content

Latest commit

 

History

History
115 lines (73 loc) · 2.59 KB

CodeTricks.md

File metadata and controls

115 lines (73 loc) · 2.59 KB

Code Tricks

Assembled & mantained by UC Davis Theoretical Population Biology group, a.k.a. Teary.

Question: How can I get my scripts to run more efficiently?

Matlab

  • Vectorize everything as matrix algebra
  • Use the matlab profiler

R

  • R profiler: Rprof (functionalize your code first)
  • sapply instead of for loops

Did you know, in R:

a/(b+c)

is slower than

a/{b+c}

and a^2 is slower than a*a.

Radford Neal pointed this out in R-2.11.1, try testing in R 2.14.1 first.

Names and speed

Although many matrix operations can be performed on data.frame, they are much faster when performed on matrix data types1.

Accesssing arrays via index is faster than by name, but using names can make for more readable code. To achieve fast access and still use names, one can construct an environment that uses a hash table for lookup

e <- new.env(hash=TRUE,size=2)
assign(x="first", value=1, envir=e)
assign(x="second", value=2, envir=e)
e

## Access via
e[["first"]]
get("second", env=e)

This tip is from Joseph Adler, who goes throught the speed improvements of this method verus named arrays.

Compiling code

As of R 2.13, the compiler package lets you compile code into byte for faster processing. The basic syntax is:

compiled.function <- cmpfun(orig.function)

A demonstration here shows that it speeds some basic functions up about 4X.

Memory

  • preallocate memory

manage memory

  • free up space and display stats with gc()
  • check memory use by x using object.size(x)
  • use memory.profile()
  • use mem.limits() to get/set memory limits

Plotting for publication (From Scott)

Labels in R can be annoying to figure out. Here are some code bits that may help?

Label the value of a parameter (m) used in the plot.

eval(paste("m = ", m))

Label the value of VLE used in plot, which is part of a list of objects in a3 (and called g in that list) LE is subscript to V with V[LE] (superscript is ^)

substitute(paste(V[LE],"=",g),a3)

Use italics in a label

expression(paste("Strength of stabilizing selection ", italic(s)))

Use math symbols (see ?plotmath). With i subscript [i]

expression(paste("Local adaptation ",bar(L)[i]))

With many subscripts and with greek letters

expression(paste("Mean phenotype ",bar(mu)[i][,][z]))

Footnotes

  1. need a small example of this