On Fri, 2009-07-17 at 18:27 -0400, Evan Weiher wrote:
<snip/>
> If you use the diversity function in R, youll probably have to fix the
> cases where richness = 0 because it returns H = 0 for zero species:
>
> richness = specnumber(ex1)
> H = diversity(ex1)
> eff.rich = exp(H)
>
> for (i in 1:length(richness)) {
> if (richness[i] == 0) {eff.rich[i] = 0} else
> {eff.rich[i] = eff.rich[i]}
> }
> eff.rich
This last bit can be done far more efficiently, via
require(vegan)
## note I made this have an empty sample
ex1 <- matrix(c(0,0,0,0,
0,0,1,1,
0,1,1,1,
1,1,1,1), byrow = TRUE, ncol = 4)
richness <- specnumber(ex1)
H <- diversity(ex1)
eff.rich <- exp(H)
## index vector
want <- richness == 0
## use replacement fun
eff.rich[want] <- 0
The point is to use R's vectorised nature whenever possible as it
generally leads to cleaner code that is likely more computationally
efficient as well.
Also worth remembering is that we are dealing with floating point
computations so to be robust to the problems this can cause, we could
replace:
want <- richness == 0
with
want <- sapply(richness, function(x) isTRUE(all.equal(x, 0)))
G
--
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
Dr. Gavin Simpson [t] +44 (0)20 7679 0522
ECRC, UCL Geography, [f] +44 (0)20 7679 0565
Pearson Building, [e] gavin.simpsonATNOSPAMucl.ac.uk
Gower Street, London [w] http://www.ucl.ac.uk/~ucfagls/
UK. WC1E 6BT. [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%