Lesson 1 · Getting started
RStudio tour
Find your way around RStudio, run code and save it in a script.
The four panels
Write and save your code here.
What R is holding: your data and objects.
Where code runs and answers appear.
Your files, your charts, help pages.
Panel 1 appears once you open a script.
Talk to R
Type in the Console and press Enter:
2 + 3
10 / 4
3^2
sqrt(16)[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.
- File > New File > R Script
- Type your code.
- Put the cursor on a line and press Ctrl+Enter (Mac: Cmd+Enter). The line runs in the Console.
- Save with Ctrl+S.
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.
# Average of three test scores
(72 + 85 + 64) / 3[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.
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
73 + 75 + 52 + 43 + 88 + 67
(73 + 75 + 52 + 43 + 88 + 67) / 6
round((73 + 75 + 52 + 43 + 88 + 67) / 6)[1] 398 [1] 66.33333 [1] 66
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
# 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)[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.