#before you start, set the working directory. Please specify the path to the Chapter_1 directory in the function setwd().

#read in the data file from the raw data folder
dat<-read.csv("DATA/RAW/field_data.csv") 

#set two variables (phosphorus and inoculant) to factors   
dat$P<-as.factor(dat$P) 
dat$I<-as.factor(dat$I)   

###calculate area (in m2) and yield in kg per ha
dat$area.m2<-dat$width.m*dat$depth.m
dat$yield.kg.ha<-dat$gwt_digit.kg*(10000/dat$area.m2)

##write the edited data to the processed data directory
write.csv(dat,"DATA/PROCESSED/field_data_processed.csv")

###make boxplot of yield per treatment
#plot on native device
plot(yield.kg.ha~treatment, data=dat)

#write to results folder
pdf(file="RESULTS/boxplot.pdf", onefile=TRUE)
plot(yield.kg.ha~treatment, data=dat)
dev.off()

##analyse as factorial with blocks (group) and interaction (using linear model)
lm1<-lm(dat$yield.kg.ha~ group+P+I+P:I, data=dat)

 
#do anova
at<-anova(lm1)     

#generate model summary
slm<-summary(lm1) 

#print results
at
slm

##write anova table and summary to results directory
sink(file="RESULTS/results_file.txt")
print(noquote("anova table:"))
print(at)
print(noquote(""))
print(noquote("model summary:"))
print(slm)
sink()
