library(grid)
library(dplyr)
library(ggplot2)
library(datasets)

#set the working directory
setwd("C:/Users/~/Data")

#save data in d
d <- "C:/Users/~/REM_LPS_Pol_025.csv"

name <- tools::file_path_sans_ext(basename(d)) #Extracts file name with |basename|, and |file_path...| remove extension

#read d and store data in ds
ds <- read.table(d, header = TRUE, sep = ",", stringsAsFactors = FALSE)

values <- print(ds) #Display values for checking

ds$tsalt <- factor(ds$tsalt) #makes sure that variable tsalt (type of salt) be treated as a categorical variable
ds$salt <- factor(ds$salt) #makes sure that variable salt (Concentration of salt) be treated as a categorical variable

glm.ds <- glm(ds$REM~ # Make tha analysis for the dependent variable rem, with a gaussian distribution
                ds$tsalt + ds$poly + ds$lps, family=gaussian())

alias(glm.ds) #check collinearity among variables

#anova(glm.ds) # Generates a Analysis of Deviance Table

summary(glm.ds) # Display GLM results

confint(glm.ds) # Display the confidence interval of 95%

#save residuas plot in a png file
png(file = sprintf("%s.png", name), width=4000, height=4000, res=600)
par(mfrow = c(2, 2)) #Display residues plots as a 2 : 2 matrix
plot(glm.ds) #Generates residuals graphs for checking
dev.off()

results <- list(name, values, summary(glm.ds))

capture.output(results, file = sprintf("%s.doc", name), append = TRUE) #Gets file input name and add to output .doc file.
