2.3 Code chunks

2.3.1 Writing and executing

Open RStudio, and create a new R Script file (click the icon near the upper left that looks like a piece of paper with a green plus on it). Type the following lines into the script:

  x = rnorm(n = 1000, mean = 10, sd = 4)
  mean(x)
## [1] 10.05

Execute a command from your script by clicking within the line with your mouse (or click on the line number, or click and drag to select multiple lines at once) and clicking Run (Ctrl + Enter). You can execute lines one at a time or as a group. Try executing the lines above. Compare your output. It’s probably very close but not exactly the same! No worries—the first line creates a random normal distribution.

2.3.2 Commenting with #

It’s important to add comments throughout your script. These can function as section headers, or as notes to your future self/colleagues on what you were attempting to do. R treats anything after the # sign as a comment and ignores it when executing commands. For instance:

# Practice executing commands    
  x = rnorm(n = 1000, mean = 10, sd = 4)  # create a new object, x
  mean(x)                                 # calculate the mean of it