Running R

There are a number of ways to start R.

If R is fully installed locally on the computer OR
  1. Click the START button from the Windows task bar
  2. Click Program Files
  3. Click R2.0
  4. Click RGui
From the CD.
  1. Goto the R directory
  2. Goto the rw2000 subdirectory
  3. Goto the bib subdirectory
  4. Double Click on the RGui.exe file
The RGui window should shortly appear.


End of instructions

  R object classes

Object classes define how information in stored and displayed. The basic storage unit in R is called a vector. A vector is an array of one or more entries of the same class. The common classes include
  1. numeric - stores a number eg 1, 2.345 etc
  2. character - stores alphanumeric characters eg 'a', 'fish', 'color1'
  3. logical - stores either TRUE or FALSE
So the entries (1, 2, 3 & 4) might make up a numeric vector, whereas the entries ('Big', 'Small' & 'Tiny') would make up a character vector. To determine the class type of an object, use the following syntax (where bold font is used to represent the object whose class is to be determined).

> class(name)

End of instructions

  R object classes

Assigning entries is basically the act of defining a new object name and specifying what that object contains. For example if we wanted to store the number 10.513 as John Howards IQ, we instruct R to create a new object called (say IQ) and assign the value 10.513 to it. That is, we instruct R that IQ equals 10.513.
In R, the assignment operator is <- instead of =.

> name <- entry

So to assign IQ the value of 10.513 in R

> IQ <- 10.513

End of instructions

  Print contents

In R, print means to output (list) the contents of an object. By default, the contents are output to the screen (the default output device). It is also possible to redirect output to a file or printer if necessary. The contents of a file are 'printed' by completing the 'print()' function or by just entering the name of the object. Consider the following;

> numbers <- c(1, 4, 6, 7, 4, 345, 36, 78)
> print(numbers)
[1] 1 4 6 7 4 345 36 78
> numbers
[1] 1 4 6 7 4 345 36 78

The first line of this syntax generates and populates the numeric vector called 'numbers'. The second line uses the print function to tell R to list the contents of the 'numbers' object - the output of which appears on the third line. The forth and fifth line illustrate that the same outcome can be achieved by simply entering the name of the object.

End of instructions

  R vectors - variables

In biology, a variable is a collection of observations of the same type. For example, a variable might consist of the observed weights of individuals within a sample of 10 bush rats. Each item (or element) in the variable is of the same type (a weight) and will have been measured comparably (same techniques and units). Biological variables are therefore best represented in R by vectors.

End of instructions

  R Factors

There are a number of ways in which this can be done. One way is to use the 'factor' (makes a list into a factor) function in conjunction with the 'c' (concatenation) function.

> name <- factor(c(list of characters/words))

Another way is to use the 'gl' function (which generates factors according to specified patterns of their levels)

> name <- gl(number of levels, number of replicates, length of data set, lab=c(list of level names)))

Hence, consider the following alternative solutions;

> sex <- factor(c('Female', 'Female', 'Female', 'Female', 'Female', 'Female', 'Male', 'Male', 'Male', 'Male', 'Male', 'Male'))
OR
> sex <- factor(c(rep('Female',6),rep('Male',6)))
OR
> sex <- gl(2,6,12,lab=c('Female','Male'))

The second option uses the 'rep()' function which in this case is used to repeat the level name (eg 'Female') 6 times.

End of instructions

  Saving R scripts

To create a script file
  • Goto the RGui File menu
  • Select the New script submenu
  • A new R Editor window will appear. Copy and paste the important lines of R syntax into this window.
  • Goto the RGui File menu
  • Select the Save As submenu
  • From the Save script as dialog box, find a good location to save the script file (one that you will remember)
  • Provide a name for the file (this can be any name, but one that reflects the purpose of the script is best). The file can end in any extension as it is just a plain text file, however, to help you distinguish it as an R script file in future, it is recommended that you end the filename with '.R'

End of instructions

  Quitting R

There are two ways to quit R elegantly
  1. Goto the RGui File menu and select Quit
  2. In the R Console, type

    > q()

Either way you will be prompted to save the workspace, generally this is not necessary or even desirable.

End of instructions

  The R working directory

The R working directory is the location that R looks in to read/write files. When you load R, it initially sets the working directory to a location within the R subdirectory of your computer. However, we can alter the working directory so that it points to another location. This not only prevents having to search for files, it also negates the specify a path as well as a filename in various operations.
  1. Goto the RGui File menu
  2. Select the Change dir submenu
  3. Locate the directory that contains your data and/or scripts
  4. Click OK

End of instructions

  Read in (source) an R script

There are two ways to read in (source) a R script
  1. Goto the RGui File menu and select Source R code
  2. In the R Console, type

    > source('filename')

    where 'filename' is the name of the R script file.
All commands in the file will be executed sequentially starting at the first line. Note that R will ignore everything that is on a line following the '#' character. This provides a way of inserting comments into script files (a practice that is highly encouraged as it provides a way of reminding yourself what each line of syntax does).

Note that there is an alternative way of using scripts

  1. Goto the RGui File menu and select the Open script submenu
  2. This will display the R script file in the R Editor window
  3. Syntax can then be directly cut and paste into the R Console. Again,each line will be executed sequentially and comments are ignored.
When working with multi-step analyses, it is recommended that you have the R Editor open and that syntax is entered directly into the editor and then pasted into the R Console. Then provided the R script is saved regularly, your data and analyses are safe from computer disruptions.

End of instructions

  R workspace

The R workspace stores all the objects that are created during an R session. To view a list of objects occupying the current R workshpace

> ls()

The workspace is cabable of storing huge numbers of objects, and thus it can become cluttered (with objects that you have created, but forgotten about, or many similar objects that contain similar contents) very rapidly. Whilst this does not affect the performance of R, it can lead to chronic confusion. It is advisable that you remove all unwanted objects when you have finished with them. To remove and object;

> rm(object name)

where object name is the name of the object to be removed.

When you exit R, you will be prompted for whether you want to save the workspace. You can also save the current workspace at any time by;
  • Goto the RGui File menu
  • Select the Save Workspace submenu
  • Provide a location and file name for the workspace. The default and recommended (though not necessary) file extension is .RData
A saved workspace is not in easily readable text format. Saving a workspace enables you to retrieve an entire sessions work instantly, which can be useful if you are forced to perform you analyses over multiple sittings. Furthermore, by providing different names, it is possible to maintain different workspaces for different projects.

End of instructions

  Removing objects

To remove an object

> rm(object name)

where object name is the name of the object to be removed.

End of instructions

  Exporting from Excel

  • Goto the Excel File menu
  • Select the Save As submenu
  • Provide a path and filename for the file
  • Change the Save as type to CSV (Comma delimited)
  • Click the OK button.
  • You will be warned that only the selected sheet can be saved in this format - click OK
  • You will also be warned that some of the formating might be lost - again click OK. The formating that it is refering to are things like colors and fonts, neither of which are important for data analysis.

End of instructions

  Reading data into R

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.data('filename.csv', header=T, sep=',', row.names=column)

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

As an example

> phasmid <- read.data('phasmid.csv', header=T, sep=',', row.names=1)

End of instructions

  R writing data

To export data into R, we read the empty the contents a data frame into a file. The general format of the command for writing data in from a data frame into a file is

> write.data(data frame name, 'filename.csv', quote=F, sep=',')

where data frame name is a name of the data frame to be saved and filename.csv is the name of the csv file that is to be created (or overwritten). The argument quote=F indicates that quotation marks should not be placed around entries in the file. The argument sep=',' indicates that entries in the file are separated by a comma (hence a comma delimited file).

As an example

> write.data(LEAVES, 'leaves.csv', quote=F, sep=',')

End of instructions

  R workspace

A vector is simply a array (list) of entries of the same type. For example, a numeric vector is just a list of numbers. A vector has only a single dimension - length - and thus the first entry in the vector has an index of 1 (is in position 1), the second has an index of 2 (position 2), etc. The index of an entry provides a convenient way to access entries. If a vector contained the numbers 10, 5, 8, 3.1, then the entry with index 1 is 10, at index 4 is the entry 3.1. Consider the following examples

> var <- c(4,8,2,6,9,2)
> var
[1] 4 8 2 6 9 2
> var[1]
[1] 4
> var[5]
[1] 9
> var[3:5]
[1] 2 6 9

A data frame on the other hand is not a single vector, but rather a collection of vectors. It is a matrix, consisting of columns and rows and therefore has both length and width. Consequently, each entry has a row index and a column index. Consider the following examples

> dv <- c(4,8,2,6,9,2)
> iv <- c('a','a','a','b','b','b')
> data <- data.frame(iv,dv)
> data
iv dv
1 a 4
2 a 8
3 a 2
4 b 6
5 b 9
6 b 2
> data[1] #list first section
iv
1 a
2 a
3 a
4 b
5 b
6 b
> data[,1] #list contents of first column
[1] a a a b b b
Levels: a b
> data[1,] #list contents of first row
iv dv
1 a 4
> data[3,2] #list the entry in row 3, column 2
[1] 2

End of instructions

  R 'fix()' function

The 'fix()' function provides a very rudimentary spreadsheet for data editing and entry.

> fix(data frame name)

The spreadsheet (Data Editor) will appear. A new variable can be created by clicking on a column heading and then providing a name fo r the variable as well as an indication of whether the contents are expected to be numeric (numbers) or character (contain some letters). Data are added by clicking on a cell and providing an entry. Closing the Data Editor will cause the changes to come into affect.

End of instructions

  R transformations

The following table illustrates the use of common data transmformation functions on a single numeric vector (old_var). In each case a new vector is created (new_var)

TransformationSyntax
loge

> old_var <- log(new_var)

log10

> old_var <- log10(new_var)

square root

> old_var <- sqrt(new_var)

arcsin

> old_var <- asin(sqrt(new_var))

scale (mean=0, unit variance)

> old_var <- scale(new_var)

End of instructions

  Random numbers

Random numbers are usually given as a fraction (e.g 0.713791167) between 0 and 1. These can be used to generate a series of integer numbers (e.g. 7, 1, 3, 71, 379, 1167 ...) or floating points (e.g. 0.71, 7.13, 71.37, 713.7, 91.167, ...), which in turn can be used to obtain random sampling units (based on individual ID's or random grid coordinates respectively).

R uses the Mersenne-Twister Random Number Generator (RNG) with a random number sequence cycle of 219937-1. All random number generators have what is known as a 'seed'. This is a number that uniquely identifies a series of random number sequences. Strictly, computer generated random numbers are 'psuedo-random' as the sequences themselves are predefined. However, with such a large number of possible sequences (219937-1), for all intense and purposes they are random.
By default, the initial random seed is generated from the computer clock (milliseconds field) and is therefore unbiased. However, it is also possible to specify a random seed. This is often useful for error-checking functions. However, it is also facilitates learning how to perform randomizations, as the same outcomes can be repeated. To set the seed

> set.seed(number)

where number is an integer.

End of instructions

  R loading packages

R is a highly modular piece of software, consisting of a very large number of packages. Each package defines a set of functions that can be used to perform specific tasks. Packages also include of help files and example data sets and command scripts to provide information about the full use of the functions.
The modularized nature of R means that only the packages that are necessary to perform the current tasks need to be loaded into memory. This results in a very `light-weight', fast statistical software package. Furthermore, the functionality of R can be easily extended by the creation of additional packages, rather than re-write all the software. As a result of this, and the open source license, new statistics are added to R nearly as soon as staticians publish them. New and revised packages can be freely downloaded from the (CRAN) website at any time.
During the installation process of R, a large number of packages are also installed.
To install additional packages from RGui (note that this only ever needs to be done once!)
  • Goto the Rgui Packages menu
  • Select the Install package(s) from local zip files.. submenu
  • Locate and select the name of the recently downloaded (or acquired) package in zip format.

When R is first started, only the 'base' package is loaded. This package contains an extensive collection of functions for performing most of the basic data manipulation and statistical procedures. To load additional packages for use during a session:

> library(package)

where package is the name of the package to install.

End of instructions

  Opening a data file

1. Select the Data menu..
2. Select the Import Data submenu..
3. Select the From text file submenu..

The Read Data From Text File dialog box will be displayed.
4. Supply a name that will be used to refer to the data set
5. Select COMMAS as the Field Separator
6. Click

The Open dialog box will be displayed.
7. Locate and select the file (e.g. lovett.csv)
8. Click

End of instructions

  Frequency histogram

1. Select the Graphs menu..
2. Select the Histogram.. submenu..
The Histogram dialog box will be displayed.
3. Select the variable for which the histogram is to be generated
4. Click

End of instructions

  Summary Statistics

1. Select the Statistics menu..
2. Select the Summaries.. submenu..
3. Select the Basic statistics.. submenu..
The Basic Statistics dialog box will be displayed.
4. Enter a name to call the table that will contain the summary statistics (e.g. tab)
5. Select the response variable for which the statistics/parameters are to be generated from the Variable list
6. Select the appropriate statistics from the list of available statistics
7. Click

End of instructions

  Summary Statistics by groups

1. Select the Statistics menu..
2. Select the Summaries.. submenu..
3. Select the Basic statistics.. submenu..
The Basic Statistics dialog box will be displayed.
4. Enter a name to call the table that will contain the summary statistics (e.g. tab)
5. Select the response variable for which the statistics/parameters are to be generated from the Variable list
6. Select the appropriate statistics from the list of available statistics
7. Click box

The Groups dialog box will be displayed.
8. Select the categorical (factorial) variable from the list and click
8. Click

A table of statistics will appear in the R Commander output window

End of instructions

  Selecting subsets of data

1. Select the Data menu..
2. Select the Active data set.. submenu..
3. Select the Subset active data set.. submenu..
The Subset Data Set dialog box will be displayed.
4. To include all the variables, ensure that the Include all variables checkbox is checked
5. In the Subset expression box enter a logical statement that indicates how the data is to be subsetted. For example, exclude all values of DOC that are greater than 170 (to exclude the outlier) and therefore only include those values that are less that 170, enter DOC < 170. Alternatively, you could chose to exclude the outlier using its STREAM name. To exclude this point enter STREAM. != 'Santa Cruz'.
6. In the Enter name for new data set box enter a name for a new data set. Since subsetting works by generating a new data set based on the existing data set, by convention the name that you supply should reflect the data set on which it is based as well as the way in which it is modified (subsetted). In this case a good name might be lovett_minus_SantaCruz
7. Click

Now, select perform the calculations separately on the original and modified data sets (To change the active data set, click on the blue data set display next to where it says Data set on the button bar of Rcmdr.

End of instructions

  Normal probabilities

1. Select the Distributions menu..
2. Select the Normal distribution.. submenu..
3. Select the Normal probabilities.. submenu..
The Normal probabilities dialog box will be displayed.
4. Enter the value (e.g. the probability will be the area under the curve greater than this value)
5. Enter the mean and standard deviation of the population/sample
6. Select the Upper tail option
7. Click

End of instructions

  Boxplots

1. Select the Graphs menu..
2. Select the Boxplot.. submenu..
The Boxplot dialog box will be displayed.
3. Select the variable for which the boxplot is to be generated
4. Click

End of instructions

  Boxplots

A boxplot is a graphical representation of the distribution of observations based on the 5-number summary that includes the median (50%), quartiles (25% and 75%) and data range (0% - smallest observation and 100% - largest observation). The box demonstrates where the middle 50% of the data fall and the whiskers represent the minimum and maximum observations. Outliers (extreme observations) are also represented when present.
The figure below demonstrates the relationship between the distribution of observations and a boxplot of the same observations. Normally distributed data results in symmetrical boxplots, whereas skewed distributions result in asymmetrical boxplots with each segment getting progressively larger (or smaller).


End of instructions

  EDA - Normal distribution

Parametric statistical hypothesis tests assume that the population measurements follow a specific distribution. Most commonly, statistical hypothesis tests assume that the population measurements are normally distributed (Question 4 highlights the specific reasoning for this).

While it is usually not possible to directly examine the distribution of measurements in the whole population to determine whether or not this requirement is satisfied or not (for the same reasons that it is not possible to directly measure population parameters such as population mean), if the sampling is adequate (unbiased and sufficiently replicated), the distribution of measurements in a sample should reflect the population distribution. That is a sample of measurements taken from a normally distributed population should be normally distributed.

Tests on data that do not meet the distributional requirements may not be reliable, and thus, it is essential that the distribution of data be examined routinely prior to any formal statistical analysis.


End of instructions

  EDA - Homogeneity of variances for regression

The assumption of homogeneity of variance is equally important for regression analysis and in particular, it is prospect of a relationship between the mean and variance of y-values across x-values that is of the greatest concern. Strictly the assumption is that the distribution of y values at each x value are equally varied and that there is no relationship between mean and variance. However, as we only have a single y-value for each x-value, it is difficult to determine whether the assumption of homogeneity of variance is likely to have been violated (mean of one value is meaningless and variability can't be assessed from a single value). The figure below depicts the ideal (and almost never realistic) situation in which there are multiple response variable (DV) observations for each of the levels of the predictor variable (IV). Boxplots are included that represent normality and variability.

Inferential statistics is based around repeatability and the likelihood of data re-occurrence. Consider the following scatterplot that has a regression line (linear smoother - line of best fit) fitted through the data (data points symbolized by letters).

Points that are close to the line (points A and B) of best fit (ie those points that are close to the predicted values) are likely to be highly repeatable (a repeat sampling effort is likely to yield a similar value). Conversely, points that are far from the line of best fit (such as points F and G) are likely to take on a larger variety of values.
The distance between a point (observed value) and the line of best fit (predicted value) is called a residual. A residual plot plots the each of the residuals against the expected y values. When there is a trend of increasing (or decreasing) spread of data along a regression line, the residuals will form a wedge shape pattern. Thus a wedge shape pattern in the residual plot suggests that the assumption of homogeneity of variance may have been violated.

Of course, it is also possible to assess the assumption of homogeneity of variance by simply viewing a scatterplot with a linear smoother (linear regression line) and determining whether there is a general increase or decrease in the distance that the values are from the line of best fit.


End of instructions

  EDA - Linearity

The most common methods for analysing the relationship or association between variables.assume that the variables are linearly related (or more correctly, that they do not covary according to some function other than linear). For example, to examine for the presence and strength of the relationship between two variables (such as those depicted below), it is a requirement of the more basic statistical tests that the variables not be related by any function other than a linear (straight line) function if any function at all.

There is no evidence that the data represented in Figure (a) are related (covary) according to any function other than linear. Likewise, there is no evidence that the data represented in Figure (b) are related (covary) according to any function other than linear (if at all). However, there is strong evidence that the data represented in Figure (c) are not related linearly. Hence Figure (c) depicts evidence for a violation in the statistical necessity of linearity.


End of instructions

  EDA - Scatterplots

Scatterplots are constructed to present the relationships, associations and trends between continuous variables. By convention, dependent variables are arranged on the Y-axis and independent variables on the X-axis. The variable measurements are used as coordinates and each replicate is represented by a single point.

Figure (c) above displays a linear smoother (linear `line-of-best-fit') through the data. Different smoothers help identify different trends in data.


End of instructions

  Population & sample

A population refers to all possible observations. Therefore, population parameters refer to the characteristics of the whole population. For example the population mean.

A sample represents a collected subset of the population's observations and is used to represent the entire population. Sample statistics are the characteristics of the sample (e.g. sample mean) and are used to estimate population parameters.


End of instructions

  Linear regression analysis

1. Select the Statistics menu..
2. Select the Fit models.. submenu..
3. Select the Linear model.. submenu..
The Linear Model dialog box will be displayed.
4. Enter a name to call the resulting output (the default is fine)
5. Double click on the dependent (response) variable from the Variables box. It will be added to the box on the left side of the ~
6. Double click on the independent (predictor) variable from the Variables box. It will be added to the box on the right side of the ~
Together these construct the model formula in the form of DV~IV
7. Click

End of instructions

  ANOVA

1. Select the Statistics menu..
2. Select the Fit models.. submenu..
3. Select the Linear model.. submenu..
The Linear Model dialog box will be displayed.
4. Enter a name to call the resulting output (the default is fine)
5. Double click on the dependent (response) variable from the Variables box. It will be added to the box on the left side of the ~
6. Double click on the independent (factorial) variable from the Variables box. It will be added to the box on the right side of the ~
Together these construct the model formula in the form of DV~IV
7. Click

A brief summary will appear in the R Commander output window

End of instructions

  Two-factor ANOVA

  1. Select the Statistics menu..
  2. Select the Fit models.. submenu..
  3. Select the Linear model.. submenu..
The Linear Model dialog box will be displayed.
  1. Enter a name to call the resulting output (the default is fine)
  2. Double click on the dependent (response) variable from the Variables box. It will be added to the box on the left side of the ~
  3. Double click on one of the independent (factorial) variable from the Variables box. It will be added to the box on the right side of the ~
  4. Click on the button. This is a multiplication symbol, and it will be added to the right of the first independent (factorial) variable.
  5. Together these construct the model formula in the form of DV~IV1*IV2 which R expands to into DV~IV1+IV2+IV1:IV2 (that is, the effect of factor IV1, the effect of factor IV2 and the interaction of IV1 and IV2)
  6. Click

A brief summary will appear in the R Commander output window

End of instructions

  Linear regression diagnostics

1. Select the Models menu..
2. Select the Graphs.. submenu..
3. Select the Basic diagnostic plots.. submenu..
A set of four regression diagnostic plots will be produced in the graphs window of RGui. Pay particular attention to the residual plot (top right)

End of instructions

  Residual plot

There is a residual for each point. The residuals are the differences between the predicted Y-values (point on the least squares regression line) for each X-value and the observed Y-value for each X-value. A residual plot, plots the residuals (Y-axis) against the predicted Y-values (X-axis) Plot a) shows a uniform spread of data around the least squares regression line and thus there is an even scatter of points in the residual plot (Plot b). In Plot c) the deviations of points from the predicted Y-values become greater with increasing X-values and thus there is a wedge-shape pattern in the residuals. Such a wedge suggests a violation of the homogeneity of variance assumption, and thus the regression may be unreliable.



End of instructions

  Regression output

1. Select the Models menu..
2. Select the Summarize model.. submenu..

End of instructions

  ANOVA table

1. Select the Models menu..
2. Select the Summarize model.. submenu..

End of instructions

  Copy and Paste text

  1. In the output window, highlight the text you want to copy
  2. Select the Edit.. menu..
  3. Select the Copy.. submenu..
  4. Switch focus to the program you want to paste the text into (e.g. Microsoft Word)
  5. Select the Edit.. menu. (in Word)
  6. Select the Paste.. submenu. (in Word)
  7. Switch focus back to RGui once you have finished and have produced a caption.

End of instructions

  Fully factorial ANOVA assumption checking

The assumptions of normality and homogeneity of variance apply to each of the factor level combinations, since it is the replicate observations of these that are the test residuals. If the design has two factors (IV1 and IV2) with three and four levels (groups) respectively within these factors, then a boxplot of each of the 3x4=12 combinations needs to be constructed. It is recommended that a variable (called GROUP) be setup to represent the combination of the two categorical (factor) variables.

Simply construct a boxplot with the dependent variable on the y-axis and GROUP on the x-axis. Visually assess whether the data from each group is normal (or at least that the groups are not all consistently skewed in the same direction), and whether the spread of data is each group is similar (or at least not related to the mean for that group). The GROUP variable can also assist in calculating the mean and variance for each group, to further assess variance homogeneity.

End of instructions

  Interaction plot

Interaction plots display the degree of consistency (or lack of) of the effect of one factor across each level of another factor. Interaction plots can be either bar or line graphs, however line graphs are more effective. The x-axis represents the levels of one factor, and a separate line in drawn for each level of the other factor. The following interaction plots represent two factors, A (with levels A1, A2, A3) and B (with levels B1, B2).


The parallel lines of first plot clearly indicate no interaction. The effect of factor A is consistent for both levels of factor B and visa versa. The middle plot demonstrates a moderate interaction and bottom plot illustrates a severe interaction. Clearly, whether or not there is an effect of factor B (e.g. B1 > B2 or B2 > B1) depends on the level of factor A. The trend is not consistent.

End of instructions

  Two factor ANOVA

Statistical models that incorporate more than one categorical predictor variable are broadly referred to as multivariate analysis of variance. There are two main reasons for the inclusion of multiple factors:

  1. To attempt to reduce the unexplained (or residual) variation in the response variable and therefore increase the sensitivity of the main effect test.
  2. To examine the interaction between factors. That is, whether the effect of one factor on the response variable is dependent on other factor(s) (consistent across all levels of other factor(s)).

Fully factorial linear models are used when the design incorporates two or more factors (independent, categorical variables) that are crossed with each other. That is, all combinations of the factors are included in the design and every level (group) of each factor occurs in combination with every level of the other factor(s). Furthermore, each combination is replicated.

In fully factorial designs both factors are equally important (potentially), and since all factors are crossed, we can also test whether there is an interaction between the factors (does the effect of one factor depend on the level of the other factor(s)). Graphs above depict a) interaction, b) no interaction.


For example, Quinn (1988) investigated the effects of season (two levels, winter/spring and summer/autumn) and adult density (four levels, 8, 15, 30 and 45 animals per 225cm2) on the number of limpet egg masses. As the design was fully crossed (all four densities were used in each season), he was also able to test for an interaction between season and density. That is, was the effect of density consistent across both seasons and, was the effect of season consistent across all densities.

Diagram shows layout of 2 factor fully crossed design. The two factors (each with two levels) are color (black or gray) and pattern (solid or striped). There are three experimental units (replicates) per treatment combination.


End of instructions

  Tukey's Test

  1. Select the Models.. menu..
  2. Select the Hypothesis tests.. submenu..
  3. Select the Tukey's test.. submenu..
The Tukey's Test dialog box will appear
  1. Select the factorial variable from the list
  2. Click the
The results of the Tukey's test will appear in the R Commander output window. The coefficients list the specific comparisons made. Each line represents a specific hypothesis test including difference between groups, t-value, raw p value and Tukey's adjusted p value (the other values presented are not important for BIO3011).

End of instructions

  Simple Main Effects

Before proceeding make sure you have already computed the global (multifactor ANOVA) and remember what you called the resulting model output.
  1. Select the Statistics menu..
  2. Select the Fit models.. submenu..
  3. Select the Linear model.. submenu..
The Linear Model dialog box will be displayed.
  1. Enter a name to call the resulting output (the default is fine)
  2. Double click on the dependent (response) variable from the Variables box. It will be added to the box on the left side of the ~
  3. Double click on the independent (categorical) variable that you are primarily interested from the Variables box. It will be added to the box on the right side of the ~
  4. Together these construct the model formula in the form of DV~IV
  5. In the Subset expression box, type in the name of the other categorical variable followed by == (two equals signs) and the name of one of the levels (surrounded by single quotation marks) of this factor. For example, if you had a categorical variable called TEMPERATURE and it consisted of three levels (High, Medium and Low), to perform a anova using only the High temperature data, the subset expression would be TEMPERATURE=='High'.
  6. Click
This will have performed the simple main effects ANOVA. To view the ANOVA table with the correct residual term (i.e. that from the original global anova):
  1. Select the Models menu..
  2. Select the Hypothesis tests.. submenu..
  3. Select the ANOVA table.. submenu..
The Anova table dialog box will appear
  1. Select the model that corresponds to the simple main effect from the Models list
  2. Select the Global model from the Error terms list. This is the model that contains the correct residual term that should be used for testing the simple main effects
  3. Click
The ANOVA table for the simple main effect hypothesis test will appear in the R Commander output window.

End of instructions

  Convert numeric variable into a factor

  1. Select the Data.. menu..
  2. Select the Manage variables in active data set.. submenu..
  3. Select the Convert numeric variable to factor.. submenu..
The Convert Numeric Variable to Factor dialog box will appear
  1. Select the variable to convert list
  2. Select Use numbers from the Factor Levels options
  3. Click the and accept that it is ok to overwrite an existing variable.
While there is no visible evidence that the data are any different, R will now treat the variable as a factor rather than as a numeric variable.

End of instructions

  Plot of Means

  1. Select the Graphs.. menu..
  2. Select the Plot Means.. submenu..
The Plot Means dialog box will appear
  1. Select the factorial variables from the Factorslist (do not select GROUP - this was only for assumption checking!)
  2. Select the dependent variable from the Response Variable list
  3. Click the
The interaction plot (means plot) will appear in the RGui graphics window.

End of instructions

  Tukey's Test

  1. From within Microsoft Word, double click on the pasted graph (to change to editing mode)
  2. Add labels to the bars such that common labels signify non-significant comparisons and differences between labels signify significant differences.
In the following graph the mean of group a was found to be significantly different from the means of both groups b and c whilst the means of groups b and c were not found to be significantly different from one another.


End of instructions

  Reordering factor levels

  1. Select the Data menu
  2. Select the Manage variables in active data set.. submenu
  3. Select the Reorder factor levels.. submenu
  4. Select the factorial variable whose levels you wish to reorder
  5. Click and accept that it is OK to overwrite the existing variable
The Reorder Factor Levels dialog box will appear
  1. The dialog box list the old order of the factor levels and prompts you to specify the new order. Edit the numbers in the New order boxes such that 1 signifies the factor level to be first in the order, 2 to be second and so on.
  2. Click
Note that the data as viewed or edited using either the or buttons respectively will not appear to have changed at all, but internally, R knows how to order the factor levels during analysis and plotting.

End of instructions

  Planned Comparisons

Having already performed the ANOVA..
  1. Select the Models menu
  2. Select the Hypothesis tests.. submenu
  3. Select the Planned Comparisons.. submenu
  4. Select the factorial variable and a contrast matrix will appear. It is possible to define up to n-1 planned comparisons (where n is the number of levels of the factorial variable). Note, it is not necessary to define the maximum number of comparisons.
  5. Provide a name for the comparison. For example if the first comparison is to compare level a with level b, perhaps make the label"a vs b"
  6. For each planned comparison that you are defining enter the contrast coefficients corresponding to each level of the factorial variable. For example if the factor levels are high, medium and low and you wish to compare high and low, give high a 1, medium a 0 and c low -1
  7. Click and accept that it is OK to overwrite the existing variable
An ANOVA table (incorporating the specific planned comparisons) will appear in the R Commander output window.

End of instructions

  Specific comparisons of means

Following a significant ANOVA result, it is often desirable to specifically compare group means to determine which groups are significantly different. However, multiple comparisons lead to two statistical problems. Firstly, multiple significance tests increase the Type I errors (&alpha, the probability of falsely rejecting H0). E.g., testing for differences between 5 groups requires ten pairwise comparisons. If the &alpha for each test is 0.05 (5%), then the probability of at least one Type I error for the family of 10 tests is 0.4 (40%). Secondly, the outcome of each test needs to be independent (orthogonality). E.g. if A>B and B>C then we already know the result of A vs. C.

Post-hoc unplanned pairwise comparisons (e.g. Tukey's test) compare all possible pairs of group means and are useful in an exploratory fashion to reveal major differences. Tukey's€™s test control the family-wise Type I error rate to no more that 0.05. However, this reduces the power of each of the pairwise comparisons, and only very large differences are detected (a consequence that exacerbates with an increasing number of groups).

Planned comparisons are specific comparisons that are usually planned during the design stage of the experiment. No more than (p-1, where p is the number of groups) comparisons can be made, however, each comparison (provided it is non-orthogonal) can be tested at &alpha = 0.05. Amongst all possible pairwise comparisons, specific comparisons are selected, while other meaningless (within the biological context of the investigation) are ignored.

End of instructions

  Copy and Paste graphs

1. Graph window, click the right mouse button
2. Select either the copy as metafile menu (if intending to modify/edit the graph after it is pasted into another program) or copy as bitmap (if don't intend to modify the graph after it is pasted into another program)
3. Switch control (focus) to the other program (such as Microsoft Word) using either Alt-tab or the Windows navigation buttons
4. Select the Edit.. menu. (in Word)
5. Select the Paste.. submenu. (in Word)
6. Switch focus back to RGui once you have finished and have produced a caption.

End of instructions

  ANOVA output

  1. Select the Models menu..
  2. Select the Hypothesis tests.. submenu..
  3. Select the ANOVA table.. submenu..
The Anova table dialog box will appear
  1. Select the model to be tabulated from the Models list
  2. Either leave the Error terms list blank or select the same model as from the Models list.
  3. Click
The ANOVA table will appear in the R Commander output window

End of instructions

  R2 value

The R2 value is the proportion of the total variability in the dependent variable that can be explained by its linear relationship with the independent variable, and thus a measure of the strength of the relationship. The R2 value ranges from 0 (very very low) to 1 (extremely tight relationship). The R2 value for the data represented in the following relationship would be 1 - that is all of the variation in DV can be explained by a change in IV.

The R2 value for the data represented in the next relationship however, would be substantially less than 1 - whilst some of the variation in DV can be explained by a change in IV, changes in IV alone does not account for all the changes in DV.


End of instructions

  R2 value

Essentially you need to reconstruct the linear equation (y=mx+c) that relates the dependent variable with the independent variable (including the estimated slope and y-intercept), substitute the new x value, and solve for y. Remember that if any transformations where used, then the transformation functions (eg log) need to be incorporated into the linear equation.

End of instructions

  Sample statistics

1. Select the Statistics menu..
2. Select the Summaries.. submenu..
3. Select the Numerical Summaries.. submenu..
The Numerical Summaries dialog box will be displayed.
4. Select the variable for which the summary statistic(s) are to be generated
5. Select the appropriate statistic(s)
6. Click

End of instructions

  Observations, variables & populations

Observations are the sampling units (e.g quadrats) or experimental units (e.g. individual organisms, aquaria) that make up the sample.

Variables are the actual properties measured by the individual observations (e.g. length, number of individuals, rate, pH, etc). Random variables (those variables whose values are not known for sure before the onset of sampling) can be either continuous (can theoretically be any value within a range, e.g. length, weight, pH, etc) or categorical (can only take on certain discrete values, such as counts - number of organisms etc).

Populations are defined as all the possible observations that we are interested in.

A sample represents a collected subset of the population's observations and is used to represent the entire population. Sample statistics are the characteristics of the sample (e.g. sample mean) and are used to estimate population parameters.


End of instructions

  Standard error and precision

A good indication of how good a single estimate is likely to be is how precise the measure is. Precision is a measure of how repeatable an outcome is. If we could repeat the sampling regime multiple times and each time calculate the sample mean, then we could examine how similar each of the sample means are. So a measure of precision is the degree of variability between the individual sample means from repeated sampling events.

Sample number Sample mean
112.1
212.7
312.5
Mean of sample means12.433
SD of sample means0.306

The table above lists three sample means and also illustrates a number of important points;
  1. Each sample yields a different sample mean
  2. The mean of the sample means should be the best estimate of the true population mean
  3. The more similar (consistent) the sample means are, the more precise any single estimate of the population mean is likely to be
The standard deviation of the sample means from repeated sampling is called the Standard error of the mean.

It is impractical; to repeat the sampling effort multiple times, however, it is possible to estimate the standard error (and therefore the precision of any individual sample mean) using the standard deviation (SD) of a single sample and the size (n) of this single sample.

The smaller the standard error (SE) of the mean, the more precise (and possibly more reliable) the estimate of the mean is likely to be.

End of instructions

  Confidence intervals


A 95% confidence interval is an interval that we are 95% confident will contain the true population mean. It is the interval that there is a less than 5% chance that this interval will not contain the true population mean, and therefore it is very unlikely that this interval will not contain the true mean. The frequentist approach to statistics dictates that if multiple samples are collected from a population and the interval is calculated for each sample, 95% of these intervals will contain the true population mean and 5% will not. Therefore there is a 95% probability that any single sample interval will contain the population mean.

The interval is expressed as the mean ± half the interval. The confidence interval is obviously affected by the degree of confidence. In order to have a higher degree of confidence that an interval is likely to contain the population mean, the interval would need to be larger.

End of instructions

  Data transformations


Essentially transforming data is the process of converting the scale in which the observations were measured into another scale.

I will demonstrate the principles of data transformation with two simple examples.
Firstly, to illustrate the legality and frequency of data transformations, imagine you had measured water temperature in a large number of streams. Naturally, you would have probably measured the temperature in ° C. Supposing you later wanted to publish your results in an American journal and the editor requested that the results be in ° F. You would not need to re-measure the stream temperature. Rather, each of the temperatures could be converted from one scale (° C) to the other (° F). Such transformations are very common.

To further illustrate the process of transformation, imagine a botanist wanted to examine the size of a particular species leaves for some reason. The botanist decides to measure the length of a random selection of leaves using a standard linear, metric ruler and the distribution of sample observations as represented by a histogram and boxplot are as follows.


The growth rate of leaves might be expected to be greatest in small leaves and decelerate with increasing leaf size. That is, the growth rate of leaves might be expected to be logarithmic rather than linear. As a result, the distribution of leaf sizes using a linear scale might also be expected to be non-normal (log-normal). If, instead of using a linear scale, the botanist had used a logarithmic ruler, the distribution of leaf sizes may have been more like the following.


If the distribution of observations is determined by the scale used to measure of the observations, and the choice of scale (in this case the ruler) is somewhat arbitrary (a linear scale is commonly used because we find it easier to understand), then it is justifiable to convert the data from one scale to another after the data has been collected and explored. It is not necessary to re-measure the data in a different scale. Therefore to normalize the data, the botanist can simply convert the data to logarithms.

The important points in the process of transformations are;
  1. The order of the data has not been altered (a large leaf measured on a linear scale is still a large leaf on a logarithmic scale), only the spacing of the data
  2. Since the spacing of the data is purely dependent on the scale of the measuring device, there is no reason why one scale is more correct than any other scale
  3. For the purpose of normalization, data can be converted from one scale to another following exploration

End of instructions

  Data transformations

1. Select the Data menu..
2. Select the Manage variables in active data set.. submenu..
3. Select the Compute new variable.. submenu..
The Compute new variable dialog box will be displayed.
4. Enter a name for a new variable
Note, this should be a unique name that is not already in the data set (otherwise it will be overwritten). It is good practice to simply prepend the name of the variable whose values are to be transformed with the name of the transformation function (e.g. logH - this reminds us that this new variable contains the log transformed H observations).
5. Enter the name of a transformation function with the name of the variable whose values are to be transformed as its sole argument (e.g. log10(H) - this performs a log (base 10) transformation of the H observations)
6. Click

7. Confirm the transformation by clicking either or

End of instructions

  Successful transformations


Since the objective of a transformation is primarily to normalize the data (although variance homogeneity and linearization may also be beneficial side-effects) the success of a transformation is measured by whether or not it has improved the normality of the data. It is not measured by whether the outcome of a statistical analysis is more favorable!

End of instructions

  Transformations

Biological data measured on a linear scale often follows a log-normal distribution. If however, such data was collected using a logarithmic scale (for example the length of leaves measured using a logarithmic rule rather than a standard linear rule), the observations will be normally distributed. Linear scales are usually used because they are the easiest for the feeble human mind to comprehend, but other than that, no scale is more valid for making measurements than any other scale (linear, logarithmic, ...).
 Measurements collected in one scale can be easily converted to another scale, and the resulting observations would be as if they had been measured in the new scale from the start. Therefore, it is valid to convert observations from one scale to another (transformation) for the purpose of normalizing data.
 Note, transformations only alter the distances between observations, not the order of the observations

End of instructions

  Data transformations (Log)

1. Select the Data menu..
2. Select the Manage variables in active data set submenu..
3. Select the Compute new variable submenu..
The Let dialog box will be displayed.

The Compute New Variable dialog box will be displayed.
4. Enter the name of a new variable in the New variable name box. As this is a name to refer to a new variable, it should not be an existing name
Hint: if performing a log transform, use the existing variable name with an 'L' in front
5. In the Expression to compute enter a transformation (scaling) function with the name of the existing variable to be transformed as its sole argument (e.g. log10(DOC))
6. Click
A new variable will be created, and this variable will contain the transformed values of an existing variable

End of instructions

  Scatterplots

1. Select the Graphs menu..
2. Select the Scatterplot... submenu..

The Scatterplot dialog box will be displayed.
3. Select the independent variable for the x axis
4. Select the dependent variable for the y axis
6. Click
A new scatterplot will be created that by default includes boxplots on the axes as well as both a linear regression smoother (dashed red line) and lowess smoother (solid red line)

End of instructions

  Boxplot on scatterplot axes

From the Scatterplot dialog box will be displayed.
Re-setup your scatterplot,
1. Select the independent variable for the x axis
2. Select the dependent variable for the y axis
3. Ensure that the Marginal boxplots option is selected
4. Click
A new scatterplot will be created that includes boxplots on the axes.

End of instructions

  Lowess smoother

From the Scatterplot dialog box will be displayed.
Re-setup your scatterplot,
1. Select the independent variable for the x axis
2. Select the dependent variable for the y axis
3. Ensure that the Smooth line option is selected
4. Click
A new scatterplot will be created that includes a lowess smoother through the data.

End of instructions

  Plotting y against x


The statement 'plot variable1 against variable2' is interpreted as 'plot y against x'. That is variable1 is considered to be the dependent variable and is plotted on the y-axis and variable2 is the independent variable and thus is plotted on the x-axis.

End of instructions

  Scatterplot matrix (SPLOM)

1. Select the Graphs menu..
2. Select the Scatterplot matrix... submenu..

The Scatterplot Matrix dialog box will be displayed.
3. Select the continuous variables to be included in the scatterplot matrix
4. Select the Boxplots option from the On Diagonal: options list
6. Click
A new scatterplot matrix will be created that by default includes boxplots in the diagonals as well as both a linear regression smoother (dashed black line) and lowess smoother (solid black line)

End of instructions

  EDA - Homogeneity of variance

Many statistical hypothesis tests assume that the populations from which the sample measurements were collected are equally varied with respect to all possible measurements. For example, are the growth rates of one population of plants (the population treated with a fertilizer) more or less varied than the growth rates of another population (the control population that is purely treated with water). If they are, then the results of many statistical hypothesis tests that compare means may be unreliable. If the populations are equally varied, then the tests are more likely to be reliable.
Obviously, it is not possible to determine the variability of entire populations. However, if sampling is unbiased and sufficiently replicated, then the variability of samples should be directly proportional to the variability of their respective populations. Consequently, samples that have substantially different degrees of variability provide strong evidence that the populations are likely to be unequally varied.
There are a number of options available to determine the likelihood that populations are equally varied from samples.
1. Calculate the variance or standard deviation of the populations. If one sample is more than 2 times greater or less than the other sample(s), then there is some evidence for unequal population variability (non-homogeneity of variance)
2. Construct boxplots of the measurements for each population, and compare the lengths of the boxplots. The length of a symmetrical (and thus normally distributed) boxplot is a robust measure of the spread of values, and thus an indication of the spread of population values. Therefore if any of the boxplots are more than 2 times longer or shorter than the other boxplot(s), then there is again, some evidence for unequal population variability (non-homogeneity of variance)


End of instructions

  Boxplots

1. Select the Graphs menu..
2. Select the Boxplot.. submenu..
The Boxplot dialog box will be displayed.
3. Select the variable for which the boxplot is to be generated
4. Click

5. Select the appropriate grouping variable (factor) from the list. This variable should contain two or more levels of which the boxplots are to be constructed separately.
The Groups dialog box will be displayed.
6. Click in the Groups dialog box

7. Click

End of instructions

  t test

The frequentist approach to hypothesis testing is based on estimating the probability of collecting the observed sample(s) when the null hypothesis is true. That is, how rare would it be to collect samples that displayed the observed degree of difference if the samples had been collected from identical populations. The degree of difference between two collected samples is objectively represented by a t statistic.

Where y1 and y2 are the sample means of group 1 and 2 respectively and √s²/n1 + s²/n2 represents the degree of precision in the difference between means by taking into account the degree of variability of each sample.
If the null hypothesis is true (that is the mean of population 1 and population 2 are equal), the degree of difference (t value) between an unbiased sample collected from population 1 and an unbiased sample collected from population 2 should be close to zero (0). It is unlikely that an unbiased sample collected from population 1 will have a mean substantially higher or lower than an unbiased sample from population 2. That is, it is unlikely that such samples could result in a very large (positive or negative) t value if the null hypothesis (of no difference between populations) was true. The question is, how large (either positive or negative) does the t value need to be, before we conclude that the null hypothesis is unlikely to be true?.

What is needed is a method by which we can determine the likelihood of any conceivable t value when null hypothesis is true. This can be done via simulation. We can simulate the collection of random samples from two identical populations and calculate the proportion of all possible t values.

Lets say a vivoculturalist was interested in comparing the size of Eucalyptus regnans seedlings grown under shade and full sun conditions. In this case we have two populations. One population represents all the possible E. regnans seedlings grown in shade conditions, and the other population represents all the possible E. regnans seedlings grown in full sun conditions. If we had grown 200 seedlings under shade conditions and 200 seedlings under full sun conditions, then these samples can be used to assess the null hypothesis that the mean size of an infinite number (population) of E. regnans seedlings grown under shade conditions is the same as the mean size of an infinite number (population) of E. regnans seedlings grown under full sun conditions. That is that the population means are equal.

We can firstly simulate the sizes of 200 seedlings grown under shade conditions and another 200 seedlings grown under full sun conditions that could arise naturally when shading has no effect on seedling growth. That is, we can simulate one possible outcome when the null hypothesis is true and shading has no effect on seedling growth
Now we can calculate the degree of difference between the mean sizes of seedlings grown under the two different conditions taking into account natural variation (that is, we can calculate a t value using the formula from above). From this simulation we may have found that the mean size of seedling grown in shade and full sun was 31.5cm and 33.7cm respectively and the degree of difference (t value) was 0.25. This represents only one possible outcome (t value). We now repeat this simulation process a large number of times (1000) and generate a histogram (or more correctly, a distribution) of the t value outcomes that are possible when the null hypothesis is true.

It should be obvious that when the null hypothesis is true (and the two populations are the same), the majority of t values calculated from samples containing 200 seedlings will be close to zero (0) - indicating only small degrees of difference between the samples. However, it is also important to notice that it is possible (albeit less likely) to have samples that are quit different from one another (large positive or negative t values) just by pure chance (for example t values greater than 2).

It turns out that it is not necessary to perform these simulations each time you test a null hypothesis. There is a mathematical formulae to estimate the t distribution appropriate for any given sample size (or more correctly, degrees of freedom) when the null hypothesis is true. In this case, the t distribution is for (200-1)+(200-1)=398 degrees of freedom.

At this stage we would calculate the t value from our actual observed samples (the 200 real seedlings grown under each of the conditions). We then compare this t value to our distribution of all possible t values (t distribution) to determine how likely our t value is when the null hypothesis is true. The simulated t distribution suggests that very large (positive or negative) t values are unlikely. The t distribution allows us to calculate the probability of obtaining a value greater than a specific t value. For example, we could calculate the probability of obtaining a t value of 2 or greater when the null hypothesis is true, by determining the area under the t distribution beyond a value of 2.

If the calculated t value was 2, then the probability of obtaining this t value (or one greater) when the null hypothesis is true is 0.012 (or 1.2%). Since the probability of obtaining our t value or one greater (and therefore the probability of having a sample of 200 seedlings grown in the shade being so much different in size than a sample of 200 seedlings grown in full sun) is so low, we would conclude that the null hypothesis of no effect of shading on seedling growth is likely to be false. Thus, we have provided some strong evidence that shading conditions do effect seedling growth!


End of instructions

  t-test hypothesis testing demonstration


1. Select the Demonstrations menu..
2. Select the tdistribution submenu..

The t distribution demonstration dialog box will be displayed.

The default configuration is set up to collect two random samples (one containing 8 observations, the other 6) from normally distributed populations with means of 800 and standard deviations of 20.

The intention of this demonstration is to examine the range and frequency of outcomes that are possible when the null hypothesis is true (and the two populations to be compared are equal). That is, what levels of similarities between two random samples are likely and what levels are unlikely. In the frequentist approach to hypothesis testing, likelihood is measured by how often (or how frequently) an event occurs from a large number opportunities.

Start off setting the Number of simulations to 1000. This will collect 1000 random samples from Population 1 and 2.

Assumptions - In simulating the repeated collection of samples from both male and female populations, we make a number of assumptions that have important consequences for the reliability of the statistical tests.

Firstly, the function used to simulate the collection random samples of say 8 male fulmars (and 6 female fulmars), generates these samples from normal distributions of a given mean and standard deviation. Thus, each simulated t value and the distribution of t values from multiple runs represents the situation for when the samples are collected from a population that is normally distributed. Likewise, the mathematical t distribution also makes this assumption.

Furthermore, the sampling function used the same standard deviation for each collected sample. Hence, each simulated t values and the distribution of t values from multiple runs represents the situation for when the samples are collected from populations that are equally varied. Likewise, the mathematical t distribution also makes this assumption.

By altering the variability and degree of normality of the populations, you can see the effects that normality and homogeneity of variance have on how much a distribution of t values differs from the mathematical t-distribution. Violations of either of these two assumptions (normality and homogeneity of variance) have the real potential to compromise the reliability of the statistical conclusions and thus it is important for the data to satisfy these assumptions.

End of instructions

  Basic steps of Hypothesis testing


Step 1 - Clearly establish the statistical null hypothesis. Therefore, start off by considering the situation where the null hypothesis is true - e.g. when the two population means are equal

Step 2 - Establish a critical statistical criteria (e.g. alpha = 0.05)

Step 3 - Collect samples consisting of independent, unbiased samples

Step 4 - Assess the assumptions relevant to the statistical hypothesis test. For a t test:
  1.  Normality
  2.  Homogeneity of variance

Step 5 - Calculate test statistic appropriate for null hypothesis (e.g. a t value)


Step 6 - Compare observed test statistic to a probability distribution for that test statistic when the null hypothesis is true for the appropriate degrees of freedom (e.g. compare the observed t value to a t distribution).

Step 7 - If the observed test statistic is greater (in magnitude) than the critical value for that test statistic (based on the predefined critical criteria), we conclude that it is unlikely that the observed samples could have come from populations that fulfill the null hypothesis and therefore the null hypothesis is rejected, otherwise we conclude that there is insufficient evidence to reject the null hypothesis. Alternatively, we calculate the probability of obtaining the observed test statistic (or one of greater magnitude) when the null hypothesis is true. If this probability is less than our predefined critical criteria (e.g. 0.05), we conclude that it is unlikely that the observed samples could have come from populations that fulfill the null hypothesis and therefore the null hypothesis is rejected, otherwise we conclude that there is insufficient evidence to reject the null hypothesis.

End of instructions

  Pooled variance t-test

1. Select the Statistics menu..
2. Select the Means submenu..
3. Select the Independent samples t-test... submenu..

The Independent samples t-test dialog box will be displayed.
4. Select the name of the grouping (categorical, factorial, independent) variable.
5. Select the name of the response (dependent) variable.
6. Select Yes under Assume equal variances?
7. Click
The output of the pooled variance t-test will appear in the R output window.

End of instructions

  Separate variance t-test

1. Select the Statistics menu..
2. Select the Means submenu..
3. Select the Independent samples t-test... submenu..

The Independent samples t-test dialog box will be displayed.
4. Select the name of the grouping (categorical, factorial, independent) variable.
5. Select the name of the response (dependent) variable.
6. Select No under Assume equal variances?
7. Click
The output of the pooled variance t-test will appear in the R output window.

End of instructions

  Bargraphs


1. Select the Graphs menu..
2. Select the Bargraph... submenu..

The Bar Graph dialog box will be displayed.
3. Select the name of the response (dependent) variable.
4. Select the name of the factorial variable (categorical, independent) variable. In the event that there are two categorical variables, this should be the categorical variable that contains the most levels
5. If necessary, select the name of the grouping (categorical, factorial, independent) variable.
6. Select the type of error bars to include
7. Click

The graph will appear in its own graphical window

End of instructions

  Error bars on bargraphs


From the Bar Graph dialog box
1. Select the type of error bars to include
2. Confirm that the correct dependent and categorical variables etc are highlighted
3. Click

The bargraph will be drawn with errorbars

End of instructions

  Output of t-test


The following output are based on a simulated data sets;
1.  Pooled variance t-test for populations with equal (or nearly so) variances

2.  Separate variance t-test for population with unequal variances

End of instructions

  Paired t-test

1.  Select the Statistics menu
2.  Select the Means .. submenu
3.  Select the Paired t-test submenu

From the Paired t-Test dialog box
4.  Select one of the paired variables from the First variable list
5.  Select the other paired variables from the Second variable list
6.  Click the OK button
The output of the paired t-test will appear in the R commander output window

End of instructions

  Non-parametric tests

Non-parametric tests do not place any distributional limitations on data sets and are therefore useful when the assumption of normality is violated. There are a number of alternatives to parametric tests, the most common are;

1. Randomization tests - rather than assume that a test statistic calculated from the data follows a specific mathematical distribution (such as a normal distribution), these tests generate their own test statistic distribution by repeatedly re-sampling or re-shuffling the original data and recalculating the test statistic each time. A p value is subsequently calculated as the proportion of random test statistics that are greater than or equal to the test statistic based on the original (un-shuffled) data.

2. Rank-based tests - these tests operate not on the original data, but rather data that has first been ranked (each observation is assigned a ranking, such that the largest observation is given the value of 1, the next highest is 2 and so on). It turns out that the probability distribution of any rank based test statistic for a is identical.

End of instructions

  Simple linear regression

Linear regression analysis explores the linear relationship between a continuous response variable (DV) and a single continuous predictor variable (IV). A line of best fit (one that minimizes the sum of squares deviations between the observed y values and the predicted y values at each x) is fitted to the data to estimate the linear model.

As plot a) shows, a slope of zero, would indicate no relationship – a increase in IV is not associated with a consistent change in DV.
Plot b) shows a positive relationship (positive slope) – an increase in IV is associated with an increase in DV.
Plot c) shows a negative relationship.

Testing whether the population slope (as estimated from the sample slope) is one way of evaluating the relationship. Regression analysis also determines how much of the total variability in the response variable can be explained by its linear relationship with IV, and how much remains unexplained.

The line of best fit (relating DV to IV) takes on the form of
y=mx + c
Response variable = (slope*predictor   variable) + y-intercept
If all points fall exactly on the line, then this model (right-hand part of equation) explains all of the variability in the response variable. That is, all variation in DV can be explained by differences in IV. Usually, however, the model does not explain all of the variability in the response variable (due to natural variation), some is left unexplained (referred to as error).

Therefore the linear model takes the form of;
Response variable = model + error.
A high proportion of variability explained relative to unexplained (error) is suggestive of a relationship between response and predictor variables.

For example, a mammalogist was investigating the effects of tooth wear on the amount of time free ranging koalas spend feeding per 24 h. Therefore, the amount of time spent feeding per 24 h was measured for a number of koalas that varied in their degree of tooth wear (ranging from unworn through to worn). Time spent feeding was the response variable and degree of tooth wear was the predictor variable.

End of instructions

  ANOVA

Analysis of variance, or ANOVA, partitions the variation in the response (DV) variable into that explained and that unexplained by one of more categorical predictor variables, called factors. The ratio of this partitioning can then be used to test the null hypothesis (H0) that population group or treatment means are equal. A single factor ANOVA investigates the effect of a single factor, with 2 or more groups (levels), on the response variable. Single factor ANOVA's are completely randomized (CR) designs. That is, there is no restriction on the random allocation of experimental or sampling units to factor levels.
Single factor ANOVA tests the H0 that there is no difference between the population group means.
H0: = µ1 = µ2 = .... = µi = µ
If the effect of the ith group is:
(&alphai = µi - µ) the this can be written as
H0: = &alpha1 = &alpha2 = ... = &alphai = 0
If one or more of the I are different from zero, the hull hypothesis will be rejected.

Keough and Raymondi (1995) investigated the degree to which biofilms (films of diatoms, algal spores, bacteria, and other organic material that develop on hard surfaces) influence the settlement of polychaete worms. They had four categories (levels) of the biofilm treatment: sterile substrata, lab developed biofilms without larvae, lab developed biofilms with larvae (any larvae), field developed biofilms without larvae. Biofilm plates where placed in the field in a completely randomized array. After a week the number of polychaete species settled on each plate was then recorded. The diagram illustrates an example of the spatial layout of a single factor with four treatments (four levels of the treatment factor, each with a different pattern fill) and four experimental units (replicates) for each treatment.

End of instructions

  Factorial boxplots

  1. Select the Graphs menu
  2. Select the Boxplot.. submenu
The Boxplot dialog box will appear
  1. Select the dependent variable from the Variable list
  2. Click the button
The Groups dialog box will appear
  1. Select the factorial (independent) variable from the Groups variable list
  2. Click the button
  3. Click the button
  4. The boxplot will appear in the RGui graphics window

    End of instructions

      Wilcoxon test

    1. Select the Statistics menu
    2. Select the Nonparametric tests.. submenu
    3. Select the Two-sample Wilcoxon tests.. submenu
    The Two-Sample Wilcoxon Test dialog box will appear
    1. Select the categorical (factor) variable from the Groups list
    2. Select the dependent variable from the Response Variable list
    3. Click the button
    4. You will be warned that an exact p-value cannot be computed - just ignore this!
    The results of the Wilcoxon test will appear in the R Commander output window

    End of instructions

      t-test degrees of freedom

    Degrees of freedom is the number of observations that are free to vary when estimating a parameter. For a t-test, df is calculated as
    df = (n1-1)+(n2-1)
    where n1 is population 1 sample size and n2 is the sample size of population 2.

    End of instructions

      One-tailed critical t-value

    1. Select the Distributions menu
    2. Select the t distribution.. submenu
    3. Select the t quantiles.. submenu
    The t Quantiles dialog box will appear
    1. Enter the &alpha value (usually 0.05) in the Probabilities box
    2. Enter the degrees of freedom for the test in the Degrees of freedom box
    3. It actually doesn't matter whether you select Lower tail or Upper tail. For a symmetrical distribution, centered around 0, the critical t-value is the same for both Lower tail (e.g. population 2 greater than population 1) and Upper tail (e.g. population 1 greater than population 2), except that the Lower tail is always negative. As it is often less confusing to work with positive values, it is recommended that you use Upper tail values. An example of a t-distribution with Upper tail for a one-tailed test is depicted below. Note that this is not part of the t quantiles output!

    4. Click the button
    The critical t-value will appear in the R Commander output window

    End of instructions

      Two-tailed critical t-value

    1. Select the Distributions menu
    2. Select the t distribution.. submenu
    3. Select the t quantiles.. submenu
    The t Quantiles dialog box will appear
    1. Enter the &alpha value (usually 0.025, recall that two-tail tests assign 0.05/2 to each tail) in the Probabilities box
    2. Enter the degrees of freedom for the test in the Degrees of freedom box
    3. It actually doesn't matter whether you select Lower tail or Upper tail. For a symmetrical distribution, centered around 0, the critical t-value is the same for both Lower tail (e.g. population 2 greater than population 1) and Upper tail (e.g. population 1 greater than population 2), except that the Lower tail is always negative. As it is often less confusing to work with positive values, it is recommended that you use Upper tail values. An example of a t-distribution with Upper tail for a two-tailed test is depicted below. Note that this is not part of the t quantiles output!

    4. Click the button
    The critical t-value will appear in the R Commander output window

    End of instructions

      Plotting mean vs variance

    Firstly you need to calculate the mean and variance for each level of the factorial variable.
    1. Select the Statistics menu..
    2. Select the Summaries.. submenu..
    3. Select the Basic statistics.. submenu..
    The Basic Statistics dialog box will be displayed.
    1. Note the default name that is entered in the Table name box. This can be changed to any name not already in use if you feel the need to make a more informative name
    2. Select the dependent variable
    3. Select the only the Mean and Variance options
    4. Click the button and select the factorial variable
    The Groups dialog box will be displayed.
    1. Select the categorical variable from the Groups variable list
    2. Click in the Groups dialog box
    3. Click buttons
    A table of statistics will appear in the R Commander output window


    Next you need to use this table and plot mean against variance.
    1. Click on the Data set display panel and select tab from the Select Data Set Dialog box.
    2. Select the categorical variable from the Groups variable list
    3. Click buttons
    4. Select the Graphs menu..
    5. Select the Scatterplot.. submenu..
    The Scatterplot dialog box will be displayed.
    1. Select Mean as the x-variable and Variance as the y-variable
    2. Click the button
    The plot of Mean vs Variance will appear in the RGui graphics window


    Remember to click on the Data set display panel and reselect your original data set from the Select Data Set Dialog box. This will enable you to resume working on the original data.

    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

      Goodness of fit test
    1. Select the Statistics menu..
    2. Select the Summaries.. submenu..
    3. Select the Frequency distribution.. submenu..
    The Frequency Distribution dialog box will be displayed.
  1. If a Variables list appears at the top of the dialogbox, ignore it, since we are not compiling the results from a loaded data set. If there are no active data sets, then this list will not appear.
  2. Use the Number of Columns slider to indicate the number of categories
  3. Modify the column labels one the Enter table table to reflect the data categories
  4. Enter the observed counts (frequencies) in the Enter table table
  5. In the Enter expected ratio table, enter the expected counts or ratio
  6. Click the button

The Goodness of fit test output will appear in the R Commander output window.

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

  Contingency tables
  1. Select the Statistics menu..
  2. Select the Contingency tables.. submenu..
  3. Select the Enter and analyze two-way table.. submenu..
The Enter and Analyze two-way table dialog box will be displayed.
  1. Use the Number of Columns and Number of rows sliders to indicate the number of rows and columns in the table
  2. Modify the column and row labels on the Enter counts table to reflect the data
  3. Enter the observed counts (frequencies) in the Enter table table
  4. Click the button

The Pearson's chi-squared test will appear in the R Commander output window.

End of instructions

  Contingency tables from data sets
  1. Select the Statistics menu..
  2. Select the Contingency tables.. submenu..
  3. Select the Two-way table.. submenu..
The Two-way table dialog box will be displayed.
  1. Select the row and column variables (it doesn't matter which variable is row and which is column)
  2. Click the button

The Pearson's chi-squared test and residuals will appear in the R Commander output window.

End of instructions

  Multivariate analysis

Multivariate data sets include multiple variables recorded from a number of replicate sampling or experimental units, sometimes referred to as objects. If, for example, the objects are whole organisms or ecological sampling units, the variables could be morphometric measurements or abundances of various species respectively. The variables may be all response variables (MANOVA) or they could be response variables, predictor variables or a combination of both (PCA and MDS).

The aim of multivariate analysis is to reduce the many variables to a smaller number of new derived variables that adequately summarize the original information and can be used for further analysis. In addition, Principal components analysis (PCA) and Multidimensional scaling (MDS) also aim to reveal patterns in the data, especially among objects, that could not be found by analyzing each variable separately.

End of instructions

  Bray-Curtis dissimilarity

For two objects (i = 1 and 2) and a number of variables (j = 1 to p).

  • y1j and y2j are the values of variable j in object 1 and object 2.
  • min(y1j , y2j) is the lesser value of variable j for object 1 and object 2.
  • p is the number of variables.
For example

  Var 1Var 2Var 3
Object 1369
Object 261218

BC = 1-[(2)(3+6+9)/(18+36)] = 0.33 where (3+6+9) is the lesser abundance of each variable when it occurs in each object.

Bray-Curtis dissimilarity is well suited to species abundance data because it ignores variables that have zeros for both objects, and it reaches a constant maximum value when two objects have no variables in common. However, its value is determined mainly by variables with high values (e.g. species with high abundances) and thus results are biased towards trends displayed in such variables. It ranges from 0 (objects completely similar) to 1 (objects completely dissimilar).

End of instructions

  Euclidean distance

For two objects (i = 1 and 2) and a number of variables (j = 1 to p).

  • y1j and y2j are the values of variable j in object 1 and object 2.
  • p is the number of variables.
For example

  Var 1Var 2Var 3
Object 1369
Object 261218

EUC = [(3-6)2+(6-12)2+(9-18)2] = 11.2

Euclidean distance is a very important, general, distance measure in multivariate statistics. It is based on simple geometry as a measure of distance between two objects in multidimensional space. It is only bounded by a zero for two objects with exactly the same values for all variables and has no upper limits, even when two objects have no variables in common with positive values. Since it does not reach a constant maximum value when two objects have no variables in common, it is not ideal for species abundance data.

End of instructions

  Distance measures
  1. Select the Statistics menu..
  2. Select the Dimensional analysis.. submenu..
  3. Select the Distance measures.. submenu..
The Distance Measures dialog box will be displayed.
  1. Enter a name for the output distance matrix - the default name is usually fine
  2. Select the variables (species) to include in the analysis from the Variables list
  3. Select the objects (samples/sites) to include in the analysis from the Samples/Sites list
  4. Select the Type of distance from the options
  5. Click the button

The matrix of distance values will appear in the R Commander output window.

End of instructions

  Multidimensional Scaling

Multidimensional scaling (MDS), has two aims

  • to reduce a large number of variables down to a small number of summary variables (axes) that explain most of the variation (and patterns) in the original data.
  • to reveal patterns in the data that could not be found by analysing each variable separately. For example examining which sites are most similar to one another based on the abundances of many plant species

MDS starts with a dissimilarity matrix which represents the degree of difference between all objects (such as sites or quadrats) based on all the original variables. MDS then attempts to reproduce these patterns between objects by arranging the objects in multidimensional space with the distances between each pair of objects representing their relative dissimilarity. Each of the dimensions (plot axes) therefore represents a new variable that can be used to describe the relationships between objects. A greater number of new variables (axes) increases the degree to which the original patterns between objects are retained, however less data reduction has occurred. Furthermore, it is difficult to envisage points (objects) arranged in more than three dimensions.

MDS can be broken down into the following steps

  1. Calculate a matrix of dissimilarities between objects from a data matrix (raw or standardized) in which objects (e.g. quadrats) are in rows and variables (e.g. plants) are in columns.
  2. After deciding on the number of dimensions (axes), arrange the objects in ordination (multidimensional) space (essentially a graph containing as many axes as selected dimensions) either at random or using the coordinates of a previous ordination.
  3. Move the location of the objects in space iteratively so that at each successive step, the match between the ordination inter-object distances and the dissimilarities is improved. The match between ordination distances and object dissimilarities is measured by the stress value - the lower (< 15) the stress the better the fit. Ideally < 10.
  4. The final arrangement (configuration) of objects is achieved when further iterative moving of objects no longer results in a substantial decrease in stress. Note, if final stress is > 0.2, the number of selected dimensions is inadequate.

End of instructions

  Multidimensional scaling
  1. Select the Statistics menu..
  2. Select the Dimensional analysis.. submenu..
  3. Select the Multidimensional scaling.. submenu..
The Multidimensional Scaling dialog box will be displayed.
  1. Select the name of the distance matrix to be used from the Distance matrix list
  2. Enter a name for the resulting MDS output in the Enter a name for model box. The default name is usually fine.
  3. Enter the number of new dimensions (axes) to be calculated - usually 2 or 3.
  4. Select the objects (samples/sites) to be included in the MDS from the Samples list
  5. Click the button

A large amount of information will appear in the R Commander output window (most of which you can ignore!.

  1. Scroll up through the output and locate the stress value.
  2. The RGui command prompt will prompt you to hit the return key to examine a couple of plots.

The first of these plots is a Sheppard plot which represents the relationship between the original distances (y-axis) and the new MDS distances (x-axis).
The second plot is the final ordination plot. This represents the arrangement of objects in multidimensional space.

End of instructions

  View data set
  1. Click the button within R Commander
An spreadsheet (that can't be edited) containing the data set will appear.

End of instructions