3.2 Opening RStudio

Work in RStudio is done in four windows:

  1. Script Window
    • This is were you type your R Script (.R) and where you execute commands.
    • Comparable to do-file/editor in Stata.
    • This window needs to be opened by File \(\Rightarrow\) New File \(\Rightarrow\) R Script.
  2. Console window
    • Use of R interactively. Should only be used for quick calculations and not part of an analysis.
  3. Environment
    • Lists all the variables, data frames, and user-created functions.
    • It is tempting to use the “Import Dataset” function Don’t.
  4. Plots/Packages/Help

There is a base version of R that allows doing many calculations but the power of R comes through its packages. To use functions associated with a particular package, click ``Install’’ in the packages window of RStudio and type in the name of the package. Or alternatively, use

  • install.packages("ggplot2")

To use a package, you have to activate it by either checking the box in the window “Packages” or by including library(packagename). Those packages are updated on a regular basis by users.

The # allows you to include comments in your script file that are not read by R. It is good practice to start any new script with clearing the memory using the command rm(list=ls()). Use the command get() to determine the current working directory or set the new working directory with the command setwd(), e.g., setwd("E:/"). For file paths, replace \(\backslash\) with \(/\). Next, you want to load all libraries necessary for your entire script file with the command library(). It is also good practice to save your R-script on a regular basis. The frontmatter, i.e., the top of a R-script file, could look as follows

rm(list=ls())
load("DataAnalysisPAData.RData")
library(openxlsx)

3.2.1 In-class Exercise 1

Create a R-script file with the following components:

  1. Two lines for the title and the date (use #)
  2. Clearing all current contents
  3. Setting the correct working directory
    • This should be a folder to which you have downloaded all materials.
  4. Installing and loading the package openxlsx.