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

# Web Scraping Chemical Data With R

I recently came across the problem to convert CAS numbers into SMILES and retrieve additional information about the compound.

The are several sources around the web that provide chemical informations, eg. PubChem, ChemSpider and the Chemical Identifier Resolver.

I wrote up some functions to interact from R with these servers. You can find them in my esmisc package:

These functions are very crude and need some further development (if you want to improve, fork the package!), however, here’s a short summary:

### Covert CAS to SMILES

Suppose we have some CAS numbers and want to convert them to SMILES:

##### Via ChemSpider

Note, that ChemSpider requires a security token. To obtain a token please register at ChemSpider.

### Retrieve other data from CAS

All these web resources provide additional data. Here is an example retrieving the molecular weights:

##### Via Pubchem

ChemSpider and PubChem return the same values, however the results from cactus are slightly different.

### Retrieve partitioning coefficients

Partition coefficients are another useful property. LOGKOW is a databank that contains experimental data, retrieved from the literature, on over 20,000 organic compounds.

get_kow() extracts the ‘Recommended values’ for a given CAS:

This function is very crude. For example, it returns only the first hit if multiple hits are found in the database - a better way would be to ask for user input, as we did the taxize package.

### Outlook

Currently I have no time to extensively develop these functions. I would be happy if someone picks up this work - it’s fairly easy: just fork the repo and start.

In future this could be turned into a ROpenSci package as it is within their scope.

# Collinearity

It has been quiet the last months here - main reason is that I’m working on my master’s thesis. I have already prepared some more examples from ‘Quantitative Ecotoxicolgy’, but I didn’t come to publish them here.

This post is about collinearity and the implications for linear models. The best way to explore this is by simulations - where I create data with known properties and look what happens.

### Create correlated random variables

The first problem for this simulation was: How can we create correlated random variables?

This simulation is similar to the one in Legendre & Legendre (2012) , where it is also mentioned that one could use Cholesky Decompostion to create correlated variables:

What this function function does:

• Create two normal random variables (X1, X2 ~ N(0, 1))
• Create desired correlation matrix
• Compute the Choleski factorization of the correlation matrix ( R )
• Apply the resulting matrix on the two variables (this rotates, shears and scales the variables so that they are correlated)
• Create a dependent variable y after the model:

y ~ 5 + 7*X1 + 7*X2 + e with e ~ N(0, 1)

Let’s see if it works. This creates two variables with 1000 observations with a correlation of 0.8 between them and a dependent variable.

The correlation between X1 and X2 is as desired nearly 0.8

And the data follows the specified model.

### Methods to spot collinearity

Dormann et al. (2013) lists eight methods to spot collinearity (see their Table 1). I will only show how to calculate two of those (but see the Appendix of the Dormann paper for code to all methods):

#### Absolute value of correlation coefficients r

Dormann et al. (2013) found that ‘coefficients between predictor variables of r > 0.7 was an appropriate indicator for when collinearity begins to severely distort model estimation’.

#### Variance Inflation Factors

Which is equivalent to (for variable X1):

Unfortunately there are many ‘rules of thumb’ associated with VIF: > 10, > 4, …

### Simulation 1: How does collinearity affect the precision of estimates?

Here we simulate datasets with correlations ranging from -0.8 to 0.8:

Next we fit a linear model to each of the datasets and extract the coefficients table:

Finally we extract the Standard Errors and plot them against the degree of correlation:

It can be clearly seen, that collinearity inflates the Standard Errors for the correlated variables. The intercept is not affected.

Having large standard errors parameter estimates are also variable, which is demonstrated in the next simulation:

### Simulation 2: Are estimated parameters stable under collinearity?

Here I simulate for different correlations 100 datasets each in order to see how stable the estimates are.

The code creates the datasets, fits a linear model to each dataset and extracts the estimates.

The we create a plot of the estimates for the three coefficients, each boxplot represents 100 datasets.

The red line indicates the coefficients after the data has been generated (7 * X1 and 7 * X2). We see that the spread of estimates increases as correlation increases.

This is confirmed by looking at the standard deviation of the estimates:

If the standard errors are large enough it may happen that parameter estimates may be so variable that even their sign is changed.

### References

• Carsten Dormann, Jane Elith, Sven Bacher, Carsten Buchmann, Gudrun Carl, Gabriel Carré, Jaime Marquéz, Bernd Gruber, Bruno Lafourcade, Pedro Leitão, Tamara Münkemüller, Colin McClean, Patrick Osborne, Björn Reineking, Boris Schröder, Andrew Skidmore, Damaris Zurell, Sven Lautenbach, (2013) Collinearity: a review of methods to deal with it and a simulation study evaluating their performance. Ecography 36 (1) 027-046 10.1111/j.1600-0587.2012.07348.x
• Pierre Legendre, Louis Legendre, (2012) Numerical ecology.

# Dispersion-based Weighting - a New Function in Vegan

### Intro

When analysing multivariate community data the first step is often to transform the abundance data, in order to downweight contributions of high abundance taxa to dissimilarity. There are a lot of transformations available, for example:

• log(x + 1), but see O’Hara & Kotze (2010)
• ln(2x + 1), which is used often with mesocosm data
• $x^{0.5}$
• $x^{0.25}$
• Presence/Absence
• and manymany more

However these are all global transformations (applied to every species in the dataset).

In an email discussion with Bob Clarke he pointed me to one of his papers Clarke et al. 2006:

Clarke, K. R., M. G. Chapman, P. J. Somerfield, and H. R. Needham. 2006. “Dispersion-based Weighting of Species Counts in Assemblage Analyses.” Marine Ecology. Progress Series 320: 11–27. klick

I somehow missed this paper and it looks like this hasn’t been implemented in R yet. So I wrote it up for myself and the function has been merged into vegan this week (see Changelog).

### Get it

Currently the function is only available in the dev-version of vegan. You can it easily install it from github using the devtools-package. You can also take a look at the implementation here.

The new function is named dispweight and takes three arguments:

The community data matrix, a vector describing the group structure and the number of permutations to use for the permutation test.

It returns a list of four elements:

• D: The dispersion index
• p: p-value of the permutation test
• weights: The weights applied to species
• transformed: The transformed abundance matrix

### Use it

Here it take the dune dataset and Management as grouping variable.

First we take look at the data via NMDS:

Lets run the NMDS on dispersion-weighted abundances:

In this example there is not a big difference, but as they write in their paper:

[…] we should not expect a dispersion-weighting approach to radically alter ordination and test results. Indeed, the improvements shown in the real examples of this paper are sometimes small and subtle […].

I haven’t tested the function very much, so let me know if you find any bugs! Note that the code isn’t optimised for speed and follows largely the paper.

### Refs

• KR Clarke, MG Chapman, PJ Somerfield, HR Needham, (2006) Dispersion-Based Weighting of Species Counts in Assemblage Analyses. Marine Ecology Progress Series 320 11-27 10.3354/meps320011
• Robert B. O’Hara, D. Johan Kotze, (2010) do Not Log-Transform Count Data. Methods in Ecology And Evolution 1 118-122 10.1111/j.2041-210X.2010.00021.x