Showing posts with label SAS. Show all posts
Showing posts with label SAS. Show all posts

Tuesday, January 26, 2016

Repeatability, intraclass correlation coefficient, and measurement error in R and SAS

Measurement error is "the variability of repeated measurements [...] relative to its variability among individuals in a particular group" (Bailey and Byrnes 1990, pg 124).  In other words, how  much wobble is there in repeated samples on the same individual?  I used measurement error in Curry and Patten (2014) after learning about the idea in a graduate multivariate statistics class I took a few years ago.  Papers such as Lougheed et al. (1991) and Marantz and Patten (2010) showed implementations.  I am now wanting to implement the same idea for repeated songs by the same individual bird in a species that sings one song type per individual.  How much does a bird vary in repeats of its standardized song?

I first started looking for how to implement a model II nested random effects ANOVA (as described in Bailey and Byrnes 1990), like SAS's PROC NESTED but in R, and ran into the usual problems trying to get the two programs to give equivalent output (where were my mean squares in R?  So aggravating sometimes...).  I was also looking to see exactly how a similar concept that I just learned about, repeatability (Lessells and Boag 1987; also known as the intraclass correlation coefficient), was related.  At first I thought they were the same thing, but after carefully writing out the equations from both Bailey and Byrnes (1990) and Lessells and Boag (1987), I realized they can be calculated easily from one another (and I was backed up by further reading in Wolak et al. 2012, pg. 130, who state "measurement error is simply one minus the repeatability", as I had suspected).   Measurement error uses within-groups mean square error (or variance within groups) as the numerator in the calculation, while the intraclass correlation coefficient (or repeatability) uses the among-group variance (which both Lessells and Boag 1987 and Bailey and Byrnes 1990 show to calculate using the same method).

As an aside, repeatability appears to be used rather broadly, and intraclass correlation coefficient also appears to have some other defintions, if wikipedia's summary is to be believed, but in the papers I am citing they all are comparing within and among group variation (the ANOVA framework).

Armed with this new terminology and knowledge, I decided to use the R package 'ICC' (Wolak et al. 2012) which calculates repeatability.  I tested this on some sample data from the SAS website with both the model II nested ANOVA as used in Bailey and Byrnes (1990) and in R.

Use the "turnip" dataset as the SAS website shows, then run this modified code:

   proc nested data=turnip;
      classes plant;
      var calcium;
   run;

To get this:























Calculate repeatability with these highlighted numbers using is the equation from Lessells and Boag (1987); 6 is the number of samples per individual, i.e. the number of repeated measurements:
((2.520115-0.135502)/6)/(0.135502+((2.520115-0.135502)/6))
Repeatability=0.745745

To calculate measurement error, substitute 0.135502 for the current numerator (i.e. use the Bailey and Byrnes 1990 equation).
0.135502/(0.135502+((2.520115-0.135502)/6))
Measurement error=0.254255

Adding the two numbers together gets 1, which means all the variation is accounted for (and thus you only need to calculate one; to get the other just subtract from 1).

Using the ICC package's function ICCest() gives essentially the same answer (the difference appears to be the level of precision in the decimal places), but also provides confidence intervals and other data that are explained more in the Wolak et al. paper.  (Import the data first, obviously, before running this code.  You can enter it by hand or export from SAS as a .csv).

ICCest(x=plant, y=calcium, data=turnip)

>$ICC
>[1] 0.7457443
>
>$LowerCI
>[1] 0.3889918
>
>$UpperCI
>[1] 0.9776527
>
>$N
>[1] 4
>
>$k
>[1] 6
>
>$varw
>[1] 0.1355025
>
>$vara
>[1] 0.3974355

The highlighted number is repeatability, which is essentially the same as the calculation by hand from SAS barring what I believe are differences in decimal precision used in the numbers for calculating the answer.

Finally, since SAS uses a random effects model, I hoped that one might be able to calculate measurement error by hand from R just to be sure it all works.  I found a page comparing different methods of repeatability in R that showed an example using the package 'lme4'.  Calcium is the measured variable, plant is the random effect, and there are no fixed effects.

model.repeat<-lmer(calcium~1+(1|plant),
               data=turnip)
summary(model.repeat)

>results>Linear mixed model fit by REML t-tests use Satterthwaite >approximations to degrees
>  of freedom [lmerMod]
>Formula: calcium ~ 1 + (1 | plant)
>   Data: turnip
>
>REML criterion at convergence: 31.2
>
>Scaled residuals: 
>     Min       1Q   Median       3Q      Max 
>-1.09999 -0.85753 -0.09009  0.69564  2.13276 
>
>Random effects:
> Groups   Name        Variance Std.Dev.
> plant    (Intercept) 0.3974   0.6304  
> Residual             0.1355   0.3681  
>Number of obs: 24, groups:  Plant, 4
>
>Fixed effects:
>            Estimate Std. Error    df t value Pr(>|t|)   
>(Intercept)    3.012      0.324 3.000   9.295  0.00264 **
>---
>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Use the residual (error, or within) as the numerator if you want to calculate measurement error, or the plant (among groups) variance as the numerator if you want to calculate repeatability.  For example, for measurement error, you get pretty close to the SAS-by-hand number.
0.1355/(0.3974+0.1355)
Measurement error=0.2542691

So, all three methods (by hand with lme4 in R, using the ICC package in R, and by hand from SAS PROC NESTED) give comparable results for the balanced design (for the plant dataset, n=6 for every individual plant, i.e. there are six measurements for any given plant).  For an unbalanced design, with varying numbers of measurements per group, Lessells and Boag (1987) provide an equation to calculate the appropriate sample size coefficient n0 (see their equation 5).  The ICC package uses that equation to calculate n0 (Wolak et al. 2012; this is listed as $k in the output from ICCest)  I tested this in the R packages only as I was hoping the variance from lme4 might have already been adjusted for the sample size coefficient issue.  ICC already states that they adjust (Wolak et al. 2012 and in the help file).  With the first row deleted from the turnip data set, ICC gives a repeatability value of 0.7432083 and k (which is n0 from Lessells and Boag)= 5.73913 (slightly under the previous 6, which makes sense as I deleted one row).  With that same one-row-deleted data using lme4, I took the random effects variances (0.3952/(0.1419+0.3952)) and got 0.7358034, so its variance calculation is not including the repeatability adjustment for n0.  This is not really surprising since that's not what it's designed to do.

So, what I will be doing to check for "measurement error" on my birds (how much "wobble" each bird has in its otherwise standard songs) is substitute the song variable (let's say frequency) for "calcium" and the bird ID (individual ID or band number) for "plant".  The random effect in lmer, the classes in SAS PROC NESTED, and x in ICCest are all the individual/subject/item from which you get repeated measurements for measurement error or repeatability.

Take home message: ICC is the easiest to use as it will take into account an unbalanced design for you already.  With SAS you can calculate for an unbalanced design but you'll have to do it by hand.  Thus, ICC and SAS should cover all cases.  With lme4 you can calculate repeatability and measurement error for balanced designs by hand, but I don't see a particularly obvious way to get the mean squares as in SAS (and I need to move on to other parts for the analysis), so I'm going to leave it at that for now.

Here are the papers I used to understand how to calculate measurement error and repeatability:
Bailey RC, Byrnes J. 1990. A new, old method for assessing measurement error in both univariate and multivariate morphometric studies. Systematic Biology 39:124–130.
Lessells CM, Boag PT. 1987. Unrepeatable repeatabilities: a common mistake. Auk 104:116–121.
Wolak ME, Fairbairn DJ, Paulsen YR. 2012. Guidelines for estimating repeatability.  Methods in Ecology and Evolution 3:129-137.

and here are some helpful examples of papers that use measurement error:
Lougheed SC, Arnold TW, Bailey RC. 1991. Measurement error of external and skeletal variables in birds and its effect on principal components. Auk 108:432–436.
Marantz CA, Patten MA. 2010. Quantifying subspecies analysis: a case study of morphometric variation and subspecies in the woodcreeper genus Dendrocolaptes. Ornithological Monographs 67:123–140.

Sunday, January 19, 2014

Profile analysis in SAS with R-generated figure

I was tickled to find a set of code to do a profile analysis in R hiding in a larger set of code examples.  A profile analysis is a multivariate ANOVA for repeated measures (Tabachnik and Fidell 2007).  I haven't been able to make the flatness test in SAS and R match yet using the code from the linked site, though the tests for parallelism and levels give the same results.  (I'll update the post if I figure that out).  Regardless, I really liked how the linked site made an interaction plot for a profile analysis, with pale lines for individuals shown in the background behind averages for each level.  So, what I've been doing for my profile analyses lately is using R to format the data, running the profile analysis in SAS and then graphing in R.


1. R code for formatting the data

My data are usually in column form, with each level and group as factors in two additional columns.  To get to the one-column-per-group needed for a profile analysis, I use the reshape2 package.  Follow the instructions in the melting post.  (I'll use that dataset here.)

Once you have your data in the correct format, you can export it to a .csv text file.  Make sure you have your workspace set to where you want the file to go.  (I usually do this step at the beginning when I import data, but since we generated our dataset in R, the workspace needs to be set here.)

setwd("C:\\Users\\Claire\\Documents\\")
#make sure you use two backslashes, not one.
write.csv(data.columns,file="20140116_profile_analysis.csv", na=".")
#Writes a file that can easily be imported into SAS.
#Note the na="." part, which gives periods for missing data as SAS prefers.
#My sample dataset doesn't have this, but I've left it in for when I do have a set with missing data.
#(SAS will not use those individuals in the profile analysis.)
#The file will be written to your working directory.
#You can now import it into SAS.

 

2. SAS code for analysis


The code is adapted with little change from Tabachnik and Fidell (2007), who also explain further tests you can do for your analysis.

proc glm data=whereyoukeepyourdata.dataset;
/*The profile analysis uses proc glm.*/
class levels;

/*In the class statement, levels is the variable name of you want your levels to be.*/model group1 group2 group3 group4 = levels;
/*The model statement tells you what you are testing. Here you want levels to be run on the four test grouping variables.*/
repeated teststimulus 4 profile; 

 /*This names the test1-4 variables (grouping/subtest/whatever you want to call it), so pick a descriptive name that will make interpreting your results easier.  The number after it (4) is how many groups you have.  The 'profile' turns it into a profile analysis */
title 'profile analysis';

/*This line is not required, but it makes the results easier to find if you are running more than one analysis.*/
run;

 /*runs the test*/


Here is where you get the output.  I highlight the tests for flatness (gray), parallelism (blue), and levels (yellow),



















MANOVA Test Criteria and Exact F Statistics for the Hypothesis of no teststimulus Effect
                             H = Type III SSCP Matrix for teststimulus
                                       E = Error SSCP Matrix

                                        S=1    M=0.5    N=2

          Statistic                        Value    F Value    Num DF    Den DF    Pr > F

          Wilks' Lambda               0.37200666       3.38         3         6    0.0955
          Pillai's Trace              0.62799334       3.38         3         6    0.0955
          Hotelling-Lawley Trace      1.68812389       3.38         3         6    0.0955
          Roy's Greatest Root         1.68812389       3.38         3         6    0.0955



MANOVA Test Criteria and Exact F Statistics for the Hypothesis of no teststimulus*levels Effect

                         H = Type III SSCP Matrix for teststimulus*levels
                                       E = Error SSCP Matrix

                                        S=1    M=0.5    N=2

          Statistic                        Value    F Value    Num DF    Den DF    Pr > F

          Wilks' Lambda               0.37476423       3.34         3         6    0.0975
          Pillai's Trace              0.62523577       3.34         3         6    0.0975
          Hotelling-Lawley Trace      1.66834432       3.34         3         6    0.0975
          Roy's Greatest Root         1.66834432       3.34         3         6    0.0975


The GLM Procedure
Repeated Measures Analysis of Variance

Tests of Hypotheses for Between Subjects Effects

        Source                      DF     Type III SS     Mean Square    F Value    Pr > F

        levels                       1     57.34512196     57.34512196      19.96    0.0021
        Error                        8     22.98499258      2.87312407


You then use the data from each to calculate your effect sizes.


Flatness  η2= 1 - lambda
η2= 1- 0.37200666
η2= 0.6279933


Parallelism partial η2= 1 - lambda ^ (1/2)
partial η2= 1- 0.37476423 ^ (1/2)
partial η2= 0.3878201


Levels   
η2= SS between groups / (SS between groups + SS within groups)
η2= 57.34512196 / (57.34512196 + 22.98499258)
η2= 0.7138683

3. R code for figure


This is based on the U. Florida page that I mentioned above.

#First take the data.columns and add some information on any symbols or color scheme.
#Here I'm coloring the two levels and
#adding line types (even-numbered individuals are dashed, odd are solid).

data.columns$levels.color<-data.columns$levels
data.columns$levels.color<-sub("A","blue",data.columns$levels.color)
data.columns$levels.color<-sub("B","orange",data.columns$levels.color)
data.columns$additional.linetype<-rep(c("solid", "dashed"), 5)


figure.profile<-data.columns[,c("group1",
"group2", "group3", "group4",
"additional.linetype", "levels.color")]
#Make a small matrix with just the variables needed, using the melted dataset from step 1.
#I also include two additional variables for graphing: linetype and color.
#You can code these into a new column using your factors from the original dataset.


#Some objects need to be calculated for later plotting.
(p<-ncol(figure.profile[,1:4]))
#This counts number of subscores/groups (test stimuli),
#but only the first four columns because the last two are not the data.

#Now you can create the main body of the figure.
matplot(1:p, t(as.matrix(figure.profile[,1:4])),
#1:p counts the groups, here used as the number of positions on the x-axis.
#t() transposes the matrix (created from the dataframe by as.matrix
#and using the column selection [,1:4] makes sure you only select the data columns
#and not our symbol information columns.
type="l", lwd=1, # says this is a line graph (type="l") with line width of 1.
lty=as.character(figure.profile$additional.linetype),
#the line type is given by a variable in my dataset.
#In this case, it is not part of the profile analysis,
#but is there just for visual interpretation.
#You could also use different line types to represent
#the different levels instead of color.  
#That would be particularly good
#if you need a black-and-white figure for publication.
#as.numeric is needed for it interpret it correctly.
col=as.character(figure.profile$levels.color), 
#Again, another symbol defined by a column in the dataset.
#I needed as.character to make sure it reads the factor as 
#characters, otherwise it (sometimes) gives an error
#depending on the data type in the column.


xaxt="n", #no x-axis (you'll be adding this manually soon)
main="Profile analysis",
xlab="Subtest/the repeated measurement/groups",

ylab="Dependent variable")

axis(1, 1:p, colnames(figure.profile[,1:4]))
# Add x-axis labels.
#1 is the position (the x-axis on bottom), 1:p says how many labels to add,
#and colnames takes the names from the dataset's grouping columns.
#You could also write replace colnames(figure.profile[,1:4]) with a list
#if your column names aren't tidy enough.
#axis(1, 1:p, c("Group 1", "Group 2", "Group 3", "Group 4"))



(x.bar <- by(figure.profile[,1:4], data.columns$levels, colMeans))

#Take the mean for each level across the columns 1:4 (the groups) of the matrix from above.
#The original code says to use mean but mean only works with vectors;
#colMeans works on a dataframe, which is what we have.
lines(1:p, x.bar[[1]], lwd=3, col="blue")
lines(1:p, x.bar[[2]], lwd=3, col="orange")


#These have thicker line widths (lwd=3 instead of 1) to make them stand out
#from the lines that we plotted to represent each sample.

legend("topleft", c("A", "B"), col=c("blue","orange"), lwd=3, title="Levels")
#If appropriate, add a legend to some position (here top left, but you can change this).


You now have significance tests for parallelism, levels, and groups (shown in the caption), and a clear figure showing the levels and groups for each sample and the averages.  (Your data will turn out a little different because the dataset was randomly generated in R, though the approximate differences should be the same since we set the means and standard deviations at the same values each time.)

There is no significant interaction between levels and groups (parallelism test) (Wilks' Λ=0.37, df=3,6, p=0.10, partial η2=0.39).  There is no significant difference between responses to the test groups (flatness test) (Wilks' Λ=0.37, df=3,6, p=0.10, η2=0.). There is a significant difference between levels (difference in levels test) (F1,8=19.96, p=0.002, η2=0.71).


Monday, January 06, 2014

Blog purpose and background


My goal is to provide code samples and other tutorials to help others in their analyses. Right now my coding is in three programs/languages: R, SAS, and postgreSQL.  I will also post photos from my field work and other outdoor adventures from time to time.

Where I started for each and what I'd do differently


R


I opened up a A Beginner's Guide to R (Use R!) on a rainy day in spring 2012 and spent an afternoon following the examples.  Since then, I've used a combination of google searching "what I want to do" + "in R" and a few books.  I'm pretty happy with my approach to this so far.

Details on how I'll present R code on this blog are here.

Relational databases


I grappled with this one a while and still do, so no good beginner book recommendations other than stay away from the pretty graphs in Access.  I started with Microsoft Access and those point-and-click queries in ... 2006?  Anyway, point-and-click got frustrating quickly, as that never did quite what I wanted.  I was told to query properly.  So I used JetSQL in Access.  A few years ago on the advice of a real programmer, I migrated to postgreSQL and pgadmin.

What I'd do differently: start with postgreSQL instead of Access.  It's more complicated, but so much easier to not have to convert your database from the partially automated drop-down menus in Access to an easier-to-query format later.  postgreSQL also is more powerful, which I ran into recently while trying to help a colleague use JetSQL.  Some things I was used to doing in postgreSQL were more complex or impossible in JetSQL.  I'd also have read up a little on database structuring and have thought out my database structure more.  I've had to do several big re-structurings of the architecture since I started.  I think I've finally got it where I can easily integrate new tables if needed.

Long story short: it's easier and more efficient in the long run if you just go ahead and learn to query using SQL (Structured Query Language).

SAS


I learned using code snippets from a class in 2008 and, since then, deep ventures into the help files.  I am trying to convert to R mostly, so mainly I will post SAS code to compare with R code.  Using Multivariate Statistics (Tabachnik and Fidell 2007) has lots of good SAS code to use.  So, sometimes it's simplest just to follow their examples if you have that book and a problem that it addresses.