MC³ LabCUHK Psychology

Lesson 3 · Getting started

Tables & packages

Work with a table of data, add packages, and read error messages.

In this lesson

  • Make a data frame and pick out parts of it
  • Install and load packages
  • Read error messages

You need

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

Data frames: tables

A data frame is a table. Each row is a person, each column is a variable. Let's build a small one from the first five students in our survey:

R code
students5 <- data.frame(
  ID = c("S001", "S002", "S003", "S004", "S005"),
  Gender = c("Male", "Male", "Female", "Male", "Female"),
  Age = c(20, 21, 19, 19, 21),
  ExamScore = c(73, 75, 52, 43, 88)
)
students5
Output
    ID Gender Age ExamScore
1 S001   Male  20        73
2 S002   Male  21        75
3 S003 Female  19        52
4 S004   Male  19        43
5 S005 Female  21        88

Each column is a vector, so they must all be the same length.

IDGenderAgeExamScore
1S001Male2073
2S002Male2175
3S003Female1952
4S004Male1943
5S005Female2188
students5$ExamScorepicks the yellow columnstudents5[2, ]picks the green row
R code
students5$ExamScore
mean(students5$ExamScore)
students5[2, ]
students5[students5$Gender == "Female", ]
dim(students5)
names(students5)
Output
[1] 73 75 52 43 88
[1] 66.2
    ID Gender Age ExamScore
2 S002   Male  21        75
    ID Gender Age ExamScore
3 S003 Female  19        52
5 S005 Female  21        88
[1] 5 4
[1] "ID"        "Gender"    "Age"       "ExamScore"
  • $ picks a column (press Tab after $ for a list of names).
  • [row, column] picks rows and columns. Leave one blank to mean "all".
  • dim() gives rows and columns.

Packages: add-ons

Packages add new functions to R.

Install once

Downloads it to your computer.

install.packages("tidyverse")

Load every session

Turns it on each time you open RStudio.

library(tidyverse)

Like an app: install it once, open it each time you use it.

Install everything for the course now. Run this once, in the Console. It takes a few minutes and prints a lot of red text. That's normal.

Run once in the Console
install.packages(c("tidyverse", "readxl", "haven", "psych", "rstatix", "pwr", "BSDA"))

If asked "install from sources...?", type no and press Enter.

Then load the tidyverse:

R code
library(tidyverse)
Output
── Attaching core tidyverse packages ────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2     
── Conflicts ──────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

The message lists what was loaded. "Conflicts" is normal: nothing to fix.

Reading errors

Errors are normal. Read them: they tell you what went wrong.

R code
mean(students5$examscore)
mean(Students5$ExamScore)
Output
[1] NA
Warning message:
In mean.default(students5$examscore) :
  argument is not numeric or logical: returning NA
Error: object 'Students5' not found

The first gives a warning (R still answers, but check it): there is no column examscore, so the answer is NA. The second is an error: there is no object Students5.

Message Usually means
object 'x' not found Typo, wrong capitals, or you didn't run the line that makes it
could not find function Package not loaded with library()
unexpected symbol Missing comma or bracket
there is no package called Install it first

Exercises

Exercise 3.1 Dataset: Student Life Survey (first 5 students)

Explore the table

Using students5:

  1. What is the average age?
  2. Show student 4's row.
  3. Show only the male students.
Show answerHide answer
R code
mean(students5$Age)
students5[4, ]
students5[students5$Gender == "Male", ]
Output
[1] 20
    ID Gender Age ExamScore
4 S004   Male  19        43
    ID Gender Age ExamScore
1 S001   Male  20        73
2 S002   Male  21        75
4 S004   Male  19        43
Exercise 3.2 Dataset: Student Life Survey (first 5 students)

Add a column

These students slept 6, 6, NA, 5.8, 5.5 hours a night. Add them as a new column Sleep, then find the average, ignoring the missing value.

Show hintHide hint

students5$Sleep <- c(...) creates a new column.

Show answerHide answer
R code
students5$Sleep <- c(6, 6, NA, 5.8, 5.5)
students5
mean(students5$Sleep, na.rm = TRUE)
Output
    ID Gender Age ExamScore Sleep
1 S001   Male  20        73   6.0
2 S002   Male  21        75   6.0
3 S003 Female  19        52    NA
4 S004   Male  19        43   5.8
5 S005 Female  21        88   5.5
[1] 5.825

Key points

  • A data frame is a table: rows are people, columns are variables.
  • $ picks a column; [row, column] picks rows and columns.
  • install.packages("name") once; library(name) every session.
  • Read error messages: they name the problem.