SSCC - Social Science Computing Cooperative Supporting Statistical Analysis for Research

1.7 Running your code

1.7.1 Scripts

An R script is a series of commands in a file. Scripts are ordinary text files with a file extension of .R. Commands can be sent to the console from a script using the Run icon at the top of the Source pane. An entire command can be sent, a part of a command can be run, or multiple commands can be run together. Running part of a command is a useful tool to debug nested functions.

The default working directory for a script is the project folder, when the script is part of a project. The working directory is where R will look for other files your script might need.

1.7.2 R Markdown files

An R Markdown file integrates R code and markdown code, a language used to create formatted documents from text files. The R code in R Markdown files can be inline, output from a single expression displayed in a paragraph, or in chunks, code run and displayed independent of a text paragraph.

Knitting an R Markdown file causes all the R code to be run and the output from the code is put into a markdown file. The markdown file is then run to format the final document, this includes formatting the R code results. This all happens behind the scene and you do not need to know the details about this. Each knit run the R code in a separate session, an instance of an R interpreter without any user created objects. The working directory for these session is the folder that contains the R Markdown file.

The chunks of code are where most of your development and testing time will be spent. All the code in chunk can be run using the Run Current Chunk button, a green triangle at the top right of the code chunk. All chunk before the current chunk using the Run All Chunks Above button, The gray triangle pointing down that is just to the left of Run Current Chunk button. Part of the code in a chunk can be run using the run drop down menu on the tool bar at the top of the source page.