Chapter 4: Optimizing Your Productivity
Now that we are familiar with handling many of the object types in the R interface it is time to use and save scripts, and export our workspace.
R is a programming language as we have seen, and despite the ease of typing out commands it is always better to save our commands as we type them… then the can be run later, a tremendous convenience and time-saver!
Scripts are simply a type of document that store any commands we type.. additionally we can comment within our scripts using the hash-tag character.
Using the File Menu, select File-> New -> R Script. Not surprisingly a new command line interface opens up. It is currently named Untitled. Lets give it a name (Test.Script for example). You may notice the extension for R scripts is the filename.R. Therefore, we could write our scripts in any Notepad/Wordpad type editor and save the file with the extension .R to create a working R script which can be executed from the R console.
For now lets create some dummy data to illustrate this..
# create a simple vector vector.1 <- (1:15) vector.1
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# create another simple vector time <- (1983:1997) # x vs y plot of data plot(time, vector.1)
You may notice that after inputting your commands nothing happens!! ;)
A script does not execute your commands after pressing Return or Enter. Instead we must choose to run our script via the Console. The shortcut key is Ctrl+R (to run each line successively!). Try it to generate our script now and show its content.
Lets save the script now… using Ctrl+S or File -> Save.
We can load it into any R session now using File -> Open Script.. or Ctrl+O.
The REAL use of scripts in being able to formulate a working analysis in a logical and progressive manner. Line by line we can build up a 'typical workflow' for any one type of task.
Once we have built the entire script successively we can REUSE; and REAPPLY it when needed. A well commented and well programmed script also allows others to learn, repeat, and reproduce your work. An essential part of any scientific investigation.
Note: It is important to note that with any script commands are executed regardless of who uses them! :) This may sound funny but a script is just a set of commands, like any computer program - it can only do what it has been told to!
For example if a script requires a data file (a .txt file of numbers for instance) and cannot locate that file, or it 'pointed' to the wrong directory you can expect error messages!! Therefore it is necessary to distribute your scripts bundled with the data that they may require. The one exception to this rule is data accessed over the Internet.
Navigating Through Folders
To find out which is the current directory and navigate to another we can use the following sets of commands:
# get current working directory getwd()
## [1] "C:/Users/Daniel/Desktop/Guide Markdown/Chp 4"
# use forward slash / even on Windows!! setwd("C:/Users/Daniel/Desktop/Guide Markdown/Chp 3")
To keep track of your workspace history (without using scripts) you can alternatively save your command history to a file…
# display the last 25 commands history()
## Error in history : function not supported in RStudio
# defualt is '.Rhistory' savehistory(file = "myfile")
## Error in savehistory : function not supported in RStudio
loadhistory(file = "myfile")
## Error in loadhistory : function not supported in RStudio
Saving Workspace Data and Objects
It may be even more useful to save your workspace data or individual objects, for further later analysis…
# save the workspace to the file .Rdata save.image() # saves selected object/s to file save(vector.1, file = "some_data.Rdata") # load file, cwd assumed unless path is specified! load(file = "some_data.Rdata")
Anytime you are in R and get stuck there are a few instantaneous options to get help. They should be your first stop before trying online forums like www.stackoverflow.com.
# general advice help.start()
## If nothing happens, you should open ## 'http://127.0.0.1:20908/doc/html/index.html' yourself
# help about function plot help(plot) # list all functions containing string 'plot' apropos("plot")
## [1] ".__C__recordedplot" "assocplot" "barplot" ## [4] "barplot.default" "biplot" "boxplot" ## [7] "boxplot.default" "boxplot.matrix" "boxplot.stats" ## [10] "cdplot" "coplot" "fourfoldplot" ## [13] "hook_plot_custom" "hook_plot_html" "hook_plot_md" ## [16] "hook_plot_rst" "hook_plot_tex" "interaction.plot" ## [19] "lag.plot" "matplot" "monthplot" ## [22] "mosaicplot" "plot" "plot.default" ## [25] "plot.density" "plot.design" "plot.ecdf" ## [28] "plot.function" "plot.lm" "plot.mlm" ## [31] "plot.new" "plot.spec" "plot.spec.coherency" ## [34] "plot.spec.phase" "plot.stepfun" "plot.ts" ## [37] "plot.TukeyHSD" "plot.window" "plot.xy" ## [40] "preplot" "qqplot" "recordPlot" ## [43] "replayPlot" "savePlot" "screeplot" ## [46] "spineplot" "sunflowerplot" "termplot" ## [49] "ts.plot"
# show an example of function plot example(plot.ts)
## ## plt.ts> require(graphics) ## ## plt.ts> ## Multivariate ## plt.ts> z <- ts(matrix(rt(200 * 8, df = 3), 200, 8), ## plt.ts+ start = c(1961, 1), frequency = 12) ## ## plt.ts> plot(z, yax.flip = TRUE)
## ## plt.ts> plot(z, axes = FALSE, ann = FALSE, frame.plot = TRUE, ## plt.ts+ mar.multi = c(0,0,0,0), oma.multi = c(1,1,5,1))
## ## plt.ts> title("plot(ts(..), axes=FALSE, ann=FALSE, frame.plot=TRUE, mar..., oma...)") ## ## plt.ts> z <- window(z[,1:3], end = c(1969,12)) ## ## plt.ts> plot(z, type = "b") # multiple
## ## plt.ts> plot(z, plot.type="single", lty=1:3, col=4:2)
## ## plt.ts> ## A phase plot: ## plt.ts> plot(nhtemp, c(nhtemp[-1], NA), cex = .8, col="blue", ## plt.ts+ main = "Lag plot of New Haven temperatures")
## ## plt.ts> ## a clearer way to do this would be ## plt.ts> ## Not run: ## plt.ts> ##D plot(nhtemp, lag(nhtemp, 1), cex = .8, col="blue", ## plt.ts> ##D main = "Lag plot of New Haven temperatures") ## plt.ts> ## End(Not run) ## plt.ts> ## plt.ts> ## xy.lines and xy.labels are FALSE for large series: ## plt.ts> plot(lag(sunspots, 1), sunspots, pch = ".")
## ## plt.ts> SMI <- EuStockMarkets[, "SMI"] ## ## plt.ts> plot(lag(SMI, 1), SMI, pch = ".")
## ## plt.ts> plot(lag(SMI, 20), SMI, pch = ".", log = "xy", ## plt.ts+ main = "4 weeks lagged SMI stocks -- log scale", xy.lines= TRUE)