Last year I wrote two posts about web-scraping chemical data (here and here).
These were just a collection of functions living at github.
To make these functions available to a broader audience I rewrote them, added new ones and bundled them in a new R package: webchem.

Webchem is available on github and CRAN and is part of the ROpenSci project.

Functionality

Webchem is useful for all dealing with chemical data (e.g. Daniel Münch is using it for his Database of Odor Responses, I use it for my work with monitoring data).
It allows to retrieve information about chemicals from the web.

The first post of this blog was about analysing mesocosm data using Principal Response Curves (PRC).
At the of the second part of this post I mention alternatives to PRC.
I picked up this topic for my Master’s Thesis, which resulted in a paper that was published two weeks ago.

Based on 11 mesocosm data sets (thanks to the co-authors who kindly shared their data) I compared 3 different methods to analyse such data.
In this post I show how to analyse mesocosm data using Generalized Linear Models for multivariate data ($GLM_{mv}$).
Compared to PRC these have a few advantages:

no need to choose a transformation of the community reponse, GLMs provide a natural way to model count data.

better representation of the responding taxa.

there is some indication that the models have higher power (Warton et al. (2012), Szöcs et al. (2015)*).

Nevertheless, there are also some drawbacks:

$GLM_{mv}$ are computationally more expensive

The graphical presentation of results (but see below).

In this post I will demonstrate how to analyse the chlorpyrifos data set also used in the first post.

Setup and data set

First we load some packages that I use in this post.

The abundance data we will use come with the vegan package. For demonstration purposes and to save computation time I use only eight species (of the 178). Moreover, the data in this data set was log(10 * x + 1) transformed and I backtransform to the raw counts.

As always before a data analysis we first take a look at the raw data to get an impression what’s going on.

1234567891011121314

plotraw <- data.frame(abu, env)plotraw <- melt(plotraw, id.vars = c('treatment','time','replicate'))ggplot(plotraw, aes(x = time, y = value +1, col = factor(treatment)))+ geom_point()+ geom_smooth(aes(group = treatment), se =FALSE)+ facet_wrap(~variable)+ scale_y_log10()+ labs(y ='Abundance + 1', x ='Week')+ geom_vline(aes(xintercept =0))+ theme_bw()+ theme(legend.justification = c(1,0), legend.position = c(1,0), legend.key = element_blank())

We see that caenhora and cloedipt show a strong treatment related negative response with a recovery after some weeks.
This is also the case for chaoobsc, but weaker. olchaeta, binitent and gammpule might profit from treatment.
libellae and agdasphr are low in abundance and we cannot much about their response.

Fit and check models

To fit GLMs to these eight species we use the mvabund package (Wang et al. (2012)).
We first need to create a mvabund object from our abundance data

1

abu <- mvabund(abu)

Then we can try to fit a Poisson GLM with treatment, time and their interaction as predictors:

12

mod_pois <- manyglm(abu ~ factor(treatment)* factor(time), data = env, family ='poisson')

But does this model fit to the data? We can use residual plots to check the model:

1

plot(mod_pois)

The residual plot shows a pronounced fan-shape, which indicates that this model does not fit very well to the data!
Let’s try a negative binomial model (which allows accounting for overdispersion):

123

mod_nb <- manyglm(abu ~ factor(treatment)* factor(time), data = env, family ='negative.binomial')plot(mod_nb)

This fits much better, we will stick with this model…

Test hypotheses

To test hypotheses we must take the repeated measure design into account.
As in PRC, we do this by using restricted permutations (maybe there will be multivariate mixed effect models available in the future).
One permutation design would be to permute whole time series of replicated ditches (plots), keeping the order of samplings (Within(type = 'none')).
This is easily done via the permute package.

1234

control <- how(within = Within(type ='none'), plots = Plots(strata = env$replicate, type ='free'), nperm=50)permutations <- shuffleSet(nrow(abu), control = control)

The object permuations is a permutation matrix which we will use later in hypothesis testing.

Treatment x Time Interaction

One hypothesis we could test is ‘The treatment effect is constant over time’, which is the interaction between treatment and time.
To test if we have a statistically significant interaction, we first fit a model without the interaction term

12

mod_nb_nointeraction <- manyglm(abu ~ factor(treatment)+ factor(time), data = env, family ='negative.binomial')

Then we compare the two model using a Likelihood-Ratio Test. This is done with the anova() method

This indicates that caenhora, cloedipt and chaoobsc show treatment effect varying with time.

General treatment effect

We could also compare the model with interaction to a model containing only time as explaining variable.
This gives us a test for the total treatment effect (treatment + treatment x time):

1234

mod_nb_null <- manyglm(abu ~ factor(time), data = env, family ='negative.binomial')mod_treat_aov <- anova(mod_nb, mod_nb_null , bootID = permutations, p.uni='adjusted', test ='LR')

12

## Using bootID matrix from input. ## Time elapsed: 0 hr 0 min 35 sec

Period of treatment effect

Now that we know that the treatment effect is varying with time, we could further explore this interaction by testing the treatment effect at every sampling date.
This is similar to PRC.

1234567891011

mod_pt <-NULLfor(i in levels(factor(env$time))){ take_abu <- abu[env$time == i,] take_env <- env[env$time == i,]# model mod_pt[[i]]$mod <- manyglm(take_abu ~ factor(treatment), data = take_env) mod_pt[[i]]$aov <- anova(mod_pt[[i]]$mod, nBoot =100, p.uni ='adjusted', test ='LR', show.time="none") mod_pt[[i]]$sum <- summary(mod_pt[[i]]$mod, nBoot =100, p.uni ='adjusted', test ='LR')}

For every week I fit a model with treatment as explaining variable and the run a Likelihood-Ratio test. Moreover, I also return the summary of the models (will be used later for plotting). Note, that I used only 100 permutations here to safe computation time.

From the resulting list we can extract informations that we are interested in.
E.g. we could extract the p-values at every sampling week:

This indicates a treatment effect on community structure from the day of application till week 12.

Note, this test is different to the method described in the PRC post.
There I used the log-transformed treatment as continuous predictor (regression design). In contrast, I use treatment as categorical predictor (anova design) in this example, which explains the differences.

Plotting treatment effect

Let’s further investigate what’s going on graphically.
How dose the treatment effect on the community over time look like?
Which species are when responsible for this effect?

To plot the effect of treatment I extract the species deviances (a sum-of-squares equivalent). Species with a high deviance show a strong treatment effect.
The community effect is then simply the sum of species effects/deviances.

And here is plot of treatment effects over time:

1234567

devs <- ldply(mod_pt,function(x) x$aov$uni.test[2,])plotdf <- melt(devs, id.vars ='.id')ggplot(plotdf, aes(x = as.numeric(as.character(.id)), y = value, fill = variable))+ geom_area(col ='grey15')+ geom_vline(aes(xintercept =0))+ theme_bw()+ labs(x ='time', y ='Deviance (=Effect)')

We see that the treatment effect increases after chlorpyrifos application (Lo and behold!) and then lowers off (but not to the initial level).
Moreover, wee see that the contributions to the effect also change with time:
Shortly after application till week 8 caenhora, cloedipt and chaoobsc are responsible for the treatment effect. However, after week 8 the contribution of gammapule increases. Other taxa play only a minor role.

Of course, we could extract this information also numerically, similar to the explained variance in PRC.

A PRC like plot

We could also draw a PRC like plot (using the summary object from above).
The procedure is always similar: extract the necessary information (coefficients in this case),
prepare it, plot it.

This plot basically show the same patterns as the PRC.

Getting a species plot is a bit harder.
The species information displayed in standard PRC plot condenses a lot of information.
Basically, the plot shows the general species responses.
Therefore, I the general treatment test (mod_treat_aov from above) for this plot.

I first extract and calculate contribution of each species to the community response from this test:

Then I just plot the species names according to their contribution.

12345

ggplot(contr, aes(x = factor(1), y = resp *100))+ geom_text(aes(label = spec))+ labs(y ='Contribution [%]', x ='')+ theme_minimal()+ scale_x_discrete(breaks =NULL)

The only difference to the PRC is that the direction of response is not displayed.

However, the plot showing the species contribution over time (see “Plotting treatment effect”) is much more informative

Outlook

I hope this tutorial showed that applying GLMs for multivariate data to mesocosm data is not harder than performing a PRC in R.
However, currently there is no alternative to R and no graphical user interface (gui).
PRC can be also run in the commercial CANOCO software package with a nice gui.
This may hinder the adoption of these models to ecotoxicology and easy to use software is needed.

References

Warton, D.I., Wright, S.T., Wang, Y., 2012. Distance-based multivariate analyses confound location and dispersion effects. Methods in Ecology and Evolution 3, 89–101.

Szöcs, E., Van den Brink, P.J., Lagadic, L., Caquet, T., Roucaute, M., Auber, A., Bayona, Y., Liess, M., Ebke, P., Ippolito, A., ter Braak, C.J.F., Brock, T.C.M., Schäfer, R.B., 2015. Analysing chemical-induced changes in macroinvertebrate communities in aquatic mesocosm experiments: a comparison of methods. Ecotoxicology. doi:10.1007/s10646-015-1421-0

Wang, Y., Naumann, U., Wright, S.T., Warton, D.I., 2012. mvabund- an R package for model-based analysis of multivariate abundance data. Methods in Ecology and Evolution 3, 471–474.

(*) Note, the main criticism from the reviewers was that I cannot deduce power differences from the analysis of these 11 data sets. E.g. Figure 1 in Szöcs (2015) shows lower p-values for GLM, which indicates a higher power.
This annoyed me a little, so I did a (univariate) simulation study. It is currently under review and I’ll post soon about it.

Species Sensitivity Distributions (SSD) are a central tool for ecological risk
assessment (ERA).
Species show different sensitivities to chemicals and the variation between
species can be described by a statistical distribution.
A concentration at which x% of species are affected can be derived from SSDs
(= $HC_x$ ).
Usually a HC5 is derived (with 95% confidence interval) and used in ERA.

Data

In this example I will generate a SSD for the insecticide Chlorpyrifos
(CAS 2921-88-2).
SSDs are generated using data of toxicity experiments (like EC_50 / LC50 values).
Such kind of data is available e.g. from
US EPA ECOTOX database,
ECHA or
ETOX.

I prepared some data from the US EPA ECOTOX database for this post.
I will skip the data cleaning and data quality checks here - but note, this data has not
been checked thoroughly and prepared only for demonstration purposes.
However, data cleaning and checking is a very important step for every data analysis.

You can read the data into R with these three lines

12345

# download data from githubrequire(RCurl)url <- getURL("https://raw.githubusercontent.com/EDiLD/r-ed/master/post_ssd/ssd_data.csv", ssl.verifypeer =FALSE)df <- read.table(text = url, header =TRUE, sep =',', stringsAsFactors =FALSE)

A first look at the data

SSDs are typically displayed as a plot showing the fraction of affected species
on the y axis and the concentration on the x-axis.

To calculate the fraction affected we order the species by their toxicity values and then calculate the fraction:

require(ggplot2)ggplot(data = df)+ geom_point(aes(x = val, y = frac), size =5)+ geom_text(aes(x = val, y = frac, label = species), hjust =1.1, size =4)+ theme_bw()+ scale_x_log10(limits=c(0.0075, max(df$val)))+ labs(x = expression(paste('Concentration of Chlorpyrifos [ ', mu,'g ', L^-1,' ]')), y ='Fraction of species affected')

Fitting a distribution to the data

To fit a distribution to the data we can use the fitdistr() function from the MASS package or
the more flexible fitdist() from the fitdistrplus package (there are also others).
I will use the MASS package here to fit a lognormal distribution to this data.

The mean (meanlog) and standard deviation (sdlog) of the lognormal distribution were estimated from the data.
We could fit and compare (e.g. by AIC) different distributions,
but I stick with the lognormal here.

Derive HC5

From the estimated parameters of the fitted distribution we can easily extract the HC5.

To be more conservative the lower limit of the confidence interval (CI) around the HC5 is sometimes used.
The lower limit of the CI can be estimated from the data using parametric bootstrap.

The idea is:

generate random values from the fitted distribution

fit to these random values the distribution

estimate the HC5 from this new distribution

repeat many times to assess the variability of HC5 values

Alternatively, also non-parametric bootstrap could be used (resample from the data, not from the fitted distribution).

In R we write a function (myboot()) that does steps 1-3 for us:

123456789

myboot <-function(fit, p){# resample from fitted distribution xr <- rlnorm(fit$n, meanlog = fit$estimate[1], sdlog = fit$estimate[2])# fit distribition to new data fitr <- fitdistr(xr,'lognormal')# return HCp hc5r <- qlnorm(p, meanlog = fitr$estimate[1], sdlog = fitr$estimate[2])return(hc5r)}

We repeat this function 1000 times and get the quantiles of the bootstrapped HC5 values:

123

set.seed(1234)hc5_boot <- replicate(1000, myboot(fit, p =0.05))quantile(hc5_boot, probs = c(0.025,0.5,0.975))

12

## 2.5% 50% 97.5% ## 0.046027 0.102427 0.214411

So for this data and the lognormal distribution the HC5 would be 0.096 with a CI of [0.046; 0.214].

A fancy plot

Finally, I generate a fancy SSD plot with predictions (red), with bootstrapped values (blue), CI (dashed) and the raw data (dots):

This week I had to find the CAS-numbers for a bunch of pesticides.
Moreover, I also needed information about the major groups of these pesticides (e.g. herbicides, fungicides, …) and some of them were in German language.

ETOX is quite useful to find the CAS-numbers, even for German names, as they have also synonyms in their database.

Since I had > 500 compounds in my list, this was feasible to be done manually.
So I wrote two small functions (etox_to_cas() and allanwood()) to search and retrieve information from these two websites.

Both are available from my esmisc package on github.com.
These are small functions using the RCurl and XML packages for scraping.
They have not been tested very much and may not be very robust.

Query CAS from ETOX

12

require(esmisc)etox_to_cas('2,4-D')

1

## [1] "94-75-7"

If you have a bunch of compounds you can use ‘sapply()’ to feed etox_to_cas:

1

sapply(c('2,4-D','DDT','Diclopfop'), etox_to_cas)

12

## 2,4-D DDT Diclopfop ## "94-75-7" "50-29-3" NA

Query CAS and pesticide group from Allan Wood

1

allanwood('Fluazinam')

12

## CAS activity ## "79622-59-6" "fungicides (pyridine fungicides)"

To fit a ANOVA to his data we use the aov() function:

1

mod <- aov(y_asin ~ conc, data = dfm)

And summary() gives the anova table:

1

summary(mod)

12345

## Df Sum Sq Mean Sq F value Pr(>F) ## conc 5 1.575 0.3151 13.3 0.000016 ***## Residuals 18 0.426 0.0237 ## ---## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The within-treatment variance is termed Residuals and the between-treatment variance is named according to the predictor conc. The total variance is simply the sum of those and not displayed.

R already performed an F-test for us, indicated by the F value (=ratio of the Mean Sq) and Pr (>F) columns.

Multiple Comparisons

Now we know that there is a statistically significant treatment effect, we might be interested which treatments differ from the control group.

The in the book mentioned Tukey contrasts (comparing each level with each other) can be easily done with the multcomp package:

However, this leads to 15 comparisons (and tests) and we may not be interested in all. Note that we are wrong in 1 out of 20 tests ($\alpha = 0.05$) (if we do not apply correction for multiple testing).

An alternative would be just to compare the control group to the treatments. This is called Dunnett contrasts and leads to only 5 comparison.

The syntax is the same, just change Tukey to Dunnett:

The column Estimate gives use the difference in means between the control and the respective treatments and Std. Error the standard error from these estimates. Both are combined to a t value (=Estimate / Std. Error), from which we can get a p-value (P(>t)).

Note, that the p-values are already corrected for multiple testing, as indicated at the bottom of the output.
If you want to change the correction method you can use:

1

summary(glht(mod, linfct = mcp(conc ='Dunnett')), test = adjusted('bonferroni'))

This applies Bonferroni-correction, see ?p.adjust and ?adjusted for other methods.

Outlook

Warton & Hui (2011) demonstrated that the arcsine transform should not be used in either circumstance. Similarly as O’Hara & Kotze (2010) showed that count data should not be log-transformed.

I a future post I will show how to analyse this data without transformation using Generalized Linear Models (GLM) and perhabs some simulations showing that using GLM can lead to an increased statistical power for ecotoxicological data sets.

Note, that I couldn’t find any reference to Generalized Linear Models in Newman (2012) and EPA (2002), although they have been around for 30 years now (Nelder & Wedderburn, 1972).

References

Warton, D. I., & Hui, F. K. (2011). The arcsine is asinine: the analysis of proportions in ecology. Ecology, 92(1), 3-10.

O’Hara, R. B., & Kotze, D. J. (2010). Do not log‐transform count data. Methods in Ecology and Evolution, 1(2), 118-122.

Newman, M. C. (2012). Quantitative ecotoxicology. Taylor & Francis, Boca Raton, FL.

EPA (2002). Methods for Measuring the Acute Toxicity of Effluents and Receiving Waters to Freshwater and Marine Organisms.

Nelder J.A., & Wedderburn R.W.M. (1972). Generalized Linear Models. Journal of the Royal Statistical Society Series A (General) 135:370–384.