11. Saving your work

You can get R to save all of your commands and output into a “workspace” file ( with an .Rdata file extension).  Personally I don’t do this, as it is often a large file, and in any case, I have saved by commands as a script so that I can easily run them again and return to where I was very quickly.  You can find the script that I used for this course file here (right click and save Scripts.txt or Scripts.r) which contains everything in the course.  Just download it and open it in NotePad or whatever text editor you prefer.  Then simply copy the commands you wish to run, and paste them into R and hit <enter> on your keyboard if needed.

It’s also a good idea to save a dataframe once you have what you want. Then you can reload it rather than have to re-calculate things again, to save time (although R is very fast).  This is done using the write.csv function:

write.csv(data, file="data.csv", na = "NA", row.names=F)

Note, I have used the argument row.names=FALSE.  This is because when importing a data file, R automatically sequentially gives each row a number starting at 1.  Naturally we don’t what to include those row numbers in our data file when we save it!  I have also included specifying the NA values to be saved as “NA” – you could change this to whatever you wish to use.  Now we can easily re-read in our saved data and start from here in the future, rather than having to start the process from the beginning (as shown earlier):

setwd("C:/data")

data <- read.csv(file = 'data.csv', header = TRUE, sep = ',', na.strings=c("",".","NA"))

head(data) #checking it loaded and looks good

Note I have also set the working directory, to make sure that its correctly set in case I decide to only run the script from this point onwards.