# Introducing the Webchem Package

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.

Currently it provides an interface to the Chemical Identifier Resolver, chemspider, pubchem, the Chemical Translation Service and the PAN Pesticide Database. If time permits I will add other data sources (see issue page).

### webchem in action

Let’s scrape some data about Imidacloprid:

#### Chemical Identifier Resolver

Search for CAS numbers with the Chemical Identifier Resolver:

The Chemical Identifier Resolver is very powerful, see ?cir_query for possible representations. Here are just a few:

#### chemspider

To use chemspider you need a security token (see here).

The workflow is similar as in our taxize package:

1. Query ID (csid)
2. Use this ID to query more data

Two functions allow to retrieve data (normal and extended) with this ID:

#### pubchem

The same workflow applies to pubchem:

Here we get multiple matches and I use only the first one here:

cid_compinfo() then returns a lot of information from pubchem

Here I display only selected entries (see ?cid_compinfo for a list):

#### Chemical Translation Service (CTS)

CTS is very useful if you need to query different identifiers for your compound (see the CTS page for a complete list):

Let’s use CTS to query the CAS, InChIKey, chemspider ID, and pubchem id:

CTS also provides basic informations from their database. However, you need the inchikey for this:

Note, I show only a subset of all data.

#### PAN Database

The PAN database stores a lot of information and might be particularly useful for ecotoxicologists:

# Analysing Mesocosm Experiments Using Generalized Linear Models

### Introduction

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.

The explaining variables (time, treatment and replicate number) are not shipped with vegan but can be easily generated:

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

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

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

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

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):

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.

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

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

The output is twofold - first we get a multivariate test:

Which indicates that there is an interaction between treatment and time.

And second we retrieve a univariate test for every species. Here are just the p-values displayed:

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):

#### 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.

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:

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.

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) With R

## Introduction

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

## 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:

Then we can take a first look at the data:

## 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.

## parametric Bootstrap

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:

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

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):

Note, that the bootstrap function is slightly different: this is because for this plot I wanted to have for each bootstrap a different (blue) line.

# Web Scraping Pesticides Data With R

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.

Another, useful source is the Compendium of Pesticide Common Names by Allan Wood.

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

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

# Quantitative Ecotoxicology, Page 223, Example 5.1

This is example 5.1 on page 223 of Quantitative Ecotoxicology - reproduced with R.

#### Load and clean the data

Next we do some house-keeping: convert the data to long format and the concentration to factor.

Let’s have first look at the data:

#### Transform response

Next we apply the arcsine transformation:

This adds the transformed values as column y_asin to our data.frame. Survivals of 1 (100%) are transformed

, where n = number of animals per replicate.

All other values are transformed using

If we would have had observations with 0% survival, these zero values should be transformed using

by adding an extra ifelse().

Let’s look at the transformed values:

Doesn’t look that different…

#### ANOVA

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

And summary() gives the anova table:

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:

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.