Jump to main navigation


Workshop 11.2a - χ2 tests

23 April 2011

Basic χ2 references

  • Logan (2010) - Chpt 16-17
  • Quinn & Keough (2002) - Chpt 13-14

Goodness of fit test

A fictitious plant ecologist sampled 90 shrubs of a dioecious plant in a forest, and each plant was classified as being either male or female. The ecologist was interested in the sex ratio and whether it differed from 50:50. The observed counts and the predicted (expected) counts based on a theoretical 50:50 sex ratio follow.

Format of fictitious plant sex ratios - note, not a file
Expected and Observed data (50:50 sex ratio).
 FemaleMaleTotal
Observed405090
Expected454590

Tasmannia bush

Note, it is not necessary to open or create a data file for this question.

  1. First, what is the appropriate test
    to examine the sex ratio of these plants?
  2. What null hypothesis is being tested by this test?
  3. What are the degrees of freedom are associated with this data for this test?
  4. Perform a Goodness-of-fit test
    to test the null hypothesis that these data came from a population with a 50:50 sex ratio (hint). Identify the following:
    Show code
    > chisq.test(c(40, 50))
    
    	Chi-squared test for given probabilities
    
    data:  c(40, 50) 
    X-squared = 1.111, df = 1, p-value = 0.2918
    
    
    1. X2 statistic
    2. df
    3. P value
  5. What are your conclusions (statistical and biological)?
  6. Lets now extend this fictitious endeavor. Recent studies on a related species of shrub have suggested a 30:70 female:male sex ratio. Knowing that our plant ecologist had similar research interests, the authors contacted her to inquire whether her data contradicted their findings.

  7. Using the same observed data, test the null hypothesis
    that these data came from a population with a 30:70 sex ratio (hint). From a 30:70 female:male sex ratio, what are the expected frequency counts of females and males from 90 individuals and what is the X2 statistic?.
    Show code
    > chisq.test(c(40, 50), p = c(0.3, 0.7))
    
    	Chi-squared test for given probabilities
    
    data:  c(40, 50) 
    X-squared = 8.942, df = 1, p-value = 0.002787
    
    
    > chisq.test(c(40, 50), p = c(0.3, 0.7))$exp
    
    [1] 27 63
    
    1. Expected number of females
    2. Expected number of males
    3. X2 statistic
  8. Do the plant ecologist's data dispute the findings of the other studies? (y or n)

  Reading data into R

Ensure that the working directory is pointing to the path containing the file to be imported before proceeding.
To import data into R, we read the contents of a file into a data frame. The general format of the command for reading data into a data frame is

> name <- read.table('filename.csv', header=T, sep=',', row.names=column, strip.white=T)

where name is a name you wish the data frame to be referred to as, filename.csv is the name of the csv file that you created in excel and column is the number of the column that had row labels (if there were any). The argument header=T indicates that the variable (vector) names will be created from the names supplied in the first row of the file. The argument sep=',' indicates that entries in the file are separated by a comma (hence a comma delimited file). If the data file does not contain row labels, or you are not sure whether it does, it is best to omit the row.names=column argument. The strip.white=T arguement ensures that no leading or trailing spaces are left in character names (these can be particularly nasty in categorical variables!).

As an example
> phasmid <- read.data("phasmid.csv", header = T, sep = ",", row.names = 1, 
+     strip.white = T)

End of instructions

  Analysing frequencies

Analysis of frequencies is similar to Analysis of Variance (ANOVA) in some ways. Variables contain two or more classes that are defined from either natural categories or from a set of arbitrary class limits in a continuous variable. For example, the classes could be sexes (male and female) or color classes derived by splitting the light scale into a set of wavelength bands. Unlike ANOVA, in which an attribute (e.g. length) is measured for a set number of replicates and the means of different classes (categories) are compared, when analyzing frequencies, the number of replicates (observed) that fall into each of the defined classes are counted and these frequencies are compared to predicted (expected) frequencies.

Analysis of frequencies tests whether a sample of observations came from a population where the observed frequencies match some expected or theoretical frequencies. Analysis of frequencies is based on the chi-squared (X2) statistic, which follows a chi-square distribution (squared values from a standard normal distribution thus long right tail).

When there is only one categorical variable, expected frequencies are calculated from theoretical ratios. When there are more than one categorical variables, the data are arranged in a contingency table that reflects the cross-classification of sampling or experimental units into the classes of the two or more variables. The most common form of contingency table analysis (model I), tests a null hypothesis of independence between the categorical variables and is analogous to the test of an interaction in multifactorial ANOVA. Hence, frequency analysis provides hypothesis tests for solely categorical data. Although, analysis of frequencies provides a way to analyses data in which both the predictor and response variable are both categorical, since variables are not distinguished as either predictor or response in the analysis, establishment of causality is only of importance for interpretation.


End of instructions

  Goodness of fit test

The goodness-of-fit test compares observed frequencies of each class within a single categorical variable to the frequencies expected of each of the classes on a theoretical basis. It tests the null hypothesis that the sample came from a population in which the observed frequencies match the expected frequencies.

For example, an ecologist investigating factors that might lead to deviations from a 1:1 offspring sex ratio, hypothesized that when the investment in one sex is considerably greater than in the other, the offspring sex ratio should be biased towards the less costly sex. He studied two species of wasps, one of which had males that were considerably larger (and thus more costly to produce) than females. For each species, he compared the offspring sex ratio to a 1:1 ratio using a goodness-of-fit test.

End of instructions

  R Goodness of fit test

> chisq.test(c(counts))
#OR
> chisq.test(c(counts),p=c(.5,.5))

where counts is a comma separated list of observed counts or frequencies and .5,.5 is a comma separated list of expected frequencies. For example

> chisq.test(c(40,50))
#OR
> chisq.test(c(40,50),p=c(.5,.5))

End of instructions

  R Cross tables

> name.tab <- xtabs(counts ~ cat1 + cat2, data=data)

where name.tab is a name for the resulting cross table, counts are the observed counts/frequencies, cat1 and cat2 are the categorical variables and data is the name of the data frame (dataset)

End of instructions

  Contingency tables

Contingency tables are the cross-classification of two (or more) categorical variables. A 2 x 2 (two way) table takes on the following form:


Where f12 etc are the frequencies in each cell (Variable 1 x Variable 2 combination).

Contingency tables test the null hypothesis that the data came from a population in which variable 1 is independent of variable 2 and vice-versa. That is, it is a test of independence.

For example a plant ecologist examined the effect of heat on seed germination. Contingency test was used to determine whether germination (2 categories - yes or no) was independent of the heat treatment (2 categories heated or not heated).

End of instructions

  R Contingency tables

> name.x2 <- chisq.test(name.tab, correct=F)

where name.x2 is a name to provide for the fitted model and name.tab is a name of a cross table.

End of instructions

  Contingency tables from raw data sets

> name.tab <- table(data)

where name.tab is a name to give the resulting cross table and data is the name of the data set that contains the raw data.

End of instructions

  Logistic Regression

> name.glm <- glm(dv~iv, family=binomial, data=data)

where name.glm is a name you provide for the fitted model, dv is the name of the dependent variable, iv is the name of the independent variable and data is the name of the data frame (data set).

End of instructions

  Further exploration of three way log-linear interactions

Start with the female data. The female data can be accessed through the object sinclair.split[["FEMALE"]]. This is the "FEMALE" data of the sinclair.split object.

> sinclair.glmR <- glm(COUNT~DEATH+MARROW, family=poisson, data=sinclair.split[["FEMALE"]])
> sinclair.glmF <- glm(COUNT~DEATH*MARROW, family=poisson, data=sinclair.split[["FEMALE"]])
> anova(sinclair.glmR, sinclair.glmF, test="Chisq")

The first line fits the reduced log-linear model. This is the model that does not contain the two way interaction term. The second line fits the full log-linear model - the model that does contain the two way interaction. The third line generates the analysis of deviance table. This is essentially presenting the results of the hypothesis test that tests whether there is a two way interaction or not.

This same proceedure can then be repeated for the "MALE" data.

To estimate the relationship between power and sample size given degree of correlation for a range of power.

End of instructions

  Odds ratios for specific two-way interactions

Start with the female data.

> library(epitools)
> female.tab <- xtabs(COUNT ~ DEATH + MARROW, data=sinclair.split[["FEMALE"]])
> oddsratio.wald(t(female.tab))$measure
> oddsratio.wald(t(female.tab),rev="b")$measure

  1. The first line loads a package called 'epitools'. This package contains the function (oddsratiowald()) that is necessary to calculate the odds ratios.
  2. The second line converts the female data set into a cross table.
  3. The third line calculates the odds ratios and 95% confidence interval (after transposing the table). Transposing is done with the 't()' function and is necessary because oddsratio.wald is expected to only encounter a rx2 table (that is a table that only has two columns) and the odds ratios are calculated for the rows. Odds ratios are calculated by contrasting one of the levels of the row variable against the other levels. As a result, the odds ratios etc are not calculated for the first level.
  4. The final line performs the odds ratio calculations again accept this time a different level is chosen as the reference level so that all pairwise comparisons have been covered.


This same proceedure can then be repeated for the "MALE" data.

To estimate the relationship between power and sample size given degree of correlation for a range of power.

End of instructions