MC³ LabCUHK Psychology

Lesson 1 · Getting started

RStudio tour

Find your way around RStudio, run code and save it in a script.

In this lesson

  • The four panels
  • Run code with Ctrl+Enter
  • Save a script with comments

You need

Scriptlesson-01.RAll the code in this lesson, ready to run.

The four panels

Panel 1 appears once you open a script.

Talk to R

Type in the Console and press Enter:

Type in the Console
2 + 3
10 / 4
3^2
sqrt(16)
Output
[1] 5
[1] 2.5
[1] 9
[1] 4
  • [1] just means "first answer". Ignore it for now.
  • sqrt() is a function: a name, then brackets. More in Lesson 2.

Use a script

Console code is lost when you close RStudio. A script keeps it.

  1. File > New File > R Script
  2. Type your code.
  3. Put the cursor on a line and press Ctrl+Enter (Mac: Cmd+Enter). The line runs in the Console.
  4. Save with Ctrl+S.
Script Ctrl+Enter→ Console R answers→ [1] 73.66667

The loop you'll use all course: write, press Ctrl+Enter, read the answer.

Comments

Text after # is a comment. R ignores it. Use it to explain your code.

In your script
# Average of three test scores
(72 + 85 + 64) / 3
Output
[1] 73.66667

One setting to change

Tools > Global Options > General: untick Restore .RData into workspace at startup and set Save workspace to .RData on exit to Never. Your script is your record, so start fresh each time.

Exercises

These use the exam scores of the first six students in the course dataset, the Student Life Survey: 73, 75, 52, 43, 88, 67.

Exercise 1.1 Dataset: Student Life Survey (first 6 students)

Use R as a calculator

Find the total of the six exam scores, their average, and the average rounded to a whole number with round().

Show hintHide hint

Average: (73 + 75 + ...) / 6. Put the whole thing inside round( ).

Show answerHide answer
R code
73 + 75 + 52 + 43 + 88 + 67
(73 + 75 + 52 + 43 + 88 + 67) / 6
round((73 + 75 + 52 + 43 + 88 + 67) / 6)
Output
[1] 398
[1] 66.33333
[1] 66
Exercise 1.2 Dataset: Student Life Survey (first 6 students)

Save a script

Put your three lines from Exercise 1.1 in a new script, with a comment above each. Run it all (Ctrl+A, then Ctrl+Enter) and save it as exercise-01.

Show answerHide answer
R code
# Total exam score of the first six students
73 + 75 + 52 + 43 + 88 + 67

# Average exam score
(73 + 75 + 52 + 43 + 88 + 67) / 6

# Average, rounded
round((73 + 75 + 52 + 43 + 88 + 67) / 6)
Output
[1] 398
[1] 66.33333
[1] 66

Key points

  • Write code in a script, run it with Ctrl+Enter, read the answer in the Console.
  • # starts a comment.
  • + in the Console means "not finished". Esc cancels.