# Permutation test for difference in slopes # Author: Rose Keith # Calculates the difference in slopes between estimates for two variables for the observed model and 1000 # permuted data sets. # Input file: a tab-delimited .txt file with a header library(car) library(dplyr) library(lme4) datafile <- read.table('/Users/rosekeith 1/Documents/Biology/Field_data/Field_2014/field_using/KW_complete_checked_noald.txt', header=T, sep='\t', quote='') # fit linear model with the original data: observed.model<-lmer(trans_Actual_fr~Site + Veg + trans_rosPctDam + trans_cauPctDam + trans_frPctDam + Stg + (1|Site:Block) + (1|Genotype), data=datafile) # look at the results using Type III SS Anova(observed.model,Type='III') plot(observed.model) coef(summary(observed.model))%>% as.data.frame %>% filter(row.names(.)=='trans_cauPctDam') %>% # filter out everything but caudam select(`Estimate`) -> obs.cau.est # save only the Estimate for caudam coef(summary(observed.model))%>% as.data.frame %>% filter(row.names(.)=='trans_frPctDam')%>% #filter out everything but frdam select(`Estimate`)->obs.fr.est #save only the estimate for frdam obs.slope.diff <- obs.fr.est-obs.cau.est ###### Permutation Test ####### # set random number generator set.seed(777) # set number of permutations: nperm<-2000 # set number of permutations numrows<-length(datafile$Plant_ID) for (i in 1:nperm) { # copy the data frame to a new object for permuting data.perm<-datafile if (i==1) { # initialize empty data frame to store results perm.results<-data.frame('Permutation'=integer(),'Cau_est'=numeric(), 'Fr_est'=numeric(), 'Slope_diff'=numeric()) } for (n in 1:numrows){ data.perm[n,25:26]<-sample(data.perm[n,25:26]) } print(paste0("Beginning simulation number ",as.character(i))) perm.model<-lmer(trans_Actual_fr~Site + Veg + trans_rosPctDam + trans_cauPctDam + trans_frPctDam + Stg + (1|Site:Block) + (1|Genotype), data=data.perm) coef(summary(perm.model))%>% as.data.frame %>% filter(row.names(.)=='trans_cauPctDam') %>% # filter out everything but caudam select(`Estimate`) -> perm.cau.est # save only the Estimate for caudam coef(summary(perm.model))%>% as.data.frame %>% filter(row.names(.)=='trans_frPctDam')%>% #filter out everything but frdam select(`Estimate`) -> perm.fr.est #save only the estimate for frdam perm.slope.diff <- perm.fr.est-perm.cau.est perm.results<- rbind(perm.results,data.frame('Permutation'=i,'Cau_est'=perm.cau.est, "FR_est"=perm.fr.est, "Slope_diff"=perm.slope.diff)) } # View results: summary(perm.results) hist(perm.results$Estimate.2) # Divide number of larger t-values by number of permutations to get P-value.