Week 1
Intro to R

PSYC 70510 · Statistical Methods in Psych Lab I · Section 53950
Lab Instructor: Kaile Smith

This page is meant to stay open while you work in RStudio. Read one section, run the code in your own script, and compare your Console output with the output shown here.

1 What we will do today

  1. Find the Script, Console, Environment, Files, Plots, and Help panes.
  2. Create an RStudio Project and organize the course files.
  3. Create objects and vectors.
  4. Recognize numeric, character, and logical values.
  5. Import and inspect a data frame.
  6. Select rows and columns.
  7. Calculate descriptive statistics.
  8. Use the remaining class time for group work, questions, and troubleshooting.

2 R and RStudio

R is the language that reads your instructions and calculates results. RStudio is the program where you write, run, and save R code.

RStudio pane What happens there
Script Write and save code in an .R file.
Console R runs code and prints results or errors.
Environment Shows objects that currently exist.
Files, Plots, Help Browse files, view figures, and read documentation.

3 Create the course Project

An RStudio Project gives the course files one home folder. When the Project is open, R treats that folder as the working directory.

  1. Create a folder named PSYC-70510.
  2. In RStudio, choose File → New Project.
  3. Choose Existing Directory.
  4. Select the PSYC-70510 folder.
  5. Open the .Rproj file whenever you work on this course.

Inside the Project folder, create folders named data, scripts, and outputs. Keep the files organized like this:

PSYC-70510/
├── data/
│   ├── sample_data.csv
│   └── mtcars.csv
├── scripts/
│   └── StatsLab_Week1_IntroR.R
└── outputs/

3.1 Create and save an R script

An R script is the file where you write and save code. The Console will run code, but it is not where you should store your work.

  1. In RStudio, choose File → New File → R Script.
  2. A blank file will open in the Script pane.
  3. Choose File → Save As.
  4. Open the Project’s scripts folder.
  5. Name the file StatsLab_Week1_IntroR.R and select Save.

Type the following comment at the top of the new script and save again:

# Lab 1: Introduction to R

Continue adding today’s code to this script. Save it regularly with Cmd + S on a Mac or Ctrl + S on Windows.

3.2 Add comments to the Script

A comment begins with #. R ignores the rest of that line.

# Add two numbers
2 + 2

Use comments to record what the code is doing and why you are doing it.

3.3 Check the working directory

getwd() means “get working directory.” It does not need an input, so the parentheses are empty.

getwd()

Your output will contain the location of your own Project:

[1] "/Users/you/Documents/PSYC-70510"

The exact path will be different on each computer.

3.4 What is a filepath?

A filepath is the written address of a folder or file on a computer. A full filepath begins at the computer’s user folder and continues all the way to the file:

/Users/kailesmith/Documents/PSYC-70510/data/sample_data.csv

That is an example of the instructor’s filepath. Do not copy it: your computer has a different user folder and may store the Project somewhere else.

When the PSYC-70510 Project is open, R already knows the first part of the address. You can use the shorter Project-relative filepath:

data/sample_data.csv

On Windows, a full filepath often begins with something like C:/Users/your-name/. R accepts forward slashes in filepaths on both Mac and Windows.

3.5 An alternative: set the working directory manually

It is possible to tell R where to work with setwd(). The input is a full filepath to a folder:

# Instructor example only: do not copy this filepath
setwd("/Users/kailesmith/Documents/PSYC-70510")
getwd()

setwd() changes the working directory for the current R session. For this course, opening the Project is easier to reproduce because it sets the working directory automatically.

4 Create and change objects

At its simplest, you can use R like a calculator. Write this line in your Script:

2 + 2

Place the cursor on the line and press Cmd + Enter on a Mac or Ctrl + Enter on Windows. R sends the line to the Console and prints:

[1] 4

The [1] is an output label. You do not type it.

An object is a value saved under a name.

x <- 7
x

Read the line from right to left: save the value 7 under the name x.

Code Meaning
x the object name
<- assign or save
7 the value

The object x appears in the Environment after the line runs.

4.1 Character objects

Text must be placed inside quotation marks.

message <- "hello world"
message
[1] "hello world"

Running another assignment with the same name replaces the earlier value:

message <- "hello again"
message
[1] "hello again"

4.2 Numeric objects and arithmetic

x <- 7
y <- 10

x * y
x + y
y - x
y / x
[1] 70
[1] 17
[1] 3
[1] 1.428571

Save a calculated result by assigning it a new name:

x_plus_y <- x + y
x_plus_y
[1] 17

Try it yourself

Use the same assignment pattern to save the other three calculations. Type and run each line:

x_times_y <- x * y
y_minus_x <- y - x
y_div_x <- y / x

Then run the object names to check the saved results:

x_times_y
y_minus_x
y_div_x

5 Create vectors with c()

A scalar contains one value. A vector contains several values of one type. The function c() means “combine.”

z <- c(7, 9, 10, 5, 1)
z
[1] 7 9 10 5 1

R applies arithmetic to every value in a numeric vector:

z * 2
[1] 14 18 20 10 2

6 Recognize common data types

A data type tells R what kind of value it is working with.

Type Examples Meaning
numeric 21, 3.5, -8 numbers used in calculations
character "Taylor", "21" text inside quotation marks
logical TRUE, FALSE two values used for conditions

Use class() to ask R for an object’s type:

class(z)
class(message)
[1] "numeric"
[1] "character"

6.1 One vector has one common type

When a vector mixes logical values with numbers, R converts TRUE to 1 and FALSE to 0.

c(10, 7, TRUE, FALSE)
[1] 10 7 1 0

When a vector contains text, R converts every value to character text.

c(10, 7, "9", TRUE)
[1] "10" "7" "9" "TRUE"

7 Read a function call

A function performs a specific job. The values inside the parentheses are its inputs, called arguments.

Create the input vector first. NA is R’s marker for a missing value.

scores <- c(80, 92, 75, 88, NA)

Then use the vector as the first argument to mean():

mean(scores, na.rm = TRUE)
[1] 83.75
Part Meaning
mean() the function that calculates an average
scores the vector to average
na.rm an optional argument
TRUE tells mean() to remove missing values first

Function names include parentheses when we refer to the function itself: c(), class(), read.csv(), and mean().

Use ? before a function name to open its Help page:

?mean
?read.csv

8 Import a CSV file

The file sample_data.csv is inside the Project’s data folder. The relative path is therefore data/sample_data.csv.

df <- read.csv("data/sample_data.csv")

The same import could be written with a full filepath, but this instructor-specific version would only work on the instructor’s computer:

# Example only: do not copy this filepath
df <- read.csv("/Users/kailesmith/Documents/PSYC-70510/data/sample_data.csv")

Read the line in three parts:

Code Meaning
df the name of the new object
read.csv() the function that imports a CSV file
"data/sample_data.csv" the path from the open Project

Do not copy another person’s full computer path. Use the path inside your own Project.

9 Inspect the data frame

A data frame is a rectangular table. Rows are observations. Columns are variables.

Run these lines after importing df:

df
head(df)
names(df)
str(df)
class(df)
sapply(df, class)

Each line answers a different question:

Code What it shows
df the entire imported data frame
head(df) the first six rows
names(df) the column names
str(df) the number of rows and columns and each column’s type
class(df) the type of the whole object
sapply(df, class) the type of every column

sapply(df, class) means: take each column in df, apply class to it, and return all the results. The function is written as class without parentheses here because sapply() will call it for us.

10 Select one column

There are three common ways to select a column. These examples all select the same variable.

df$col_a
df[, 1]
df[, "col_a"]

Read each form literally:

Code Meaning
df$col_a look inside df and return the column named col_a
df[, 1] return all rows from column 1
df[, "col_a"] return all rows from the column named col_a

Inside square brackets, the position before the comma selects rows and the position after the comma selects columns. The general pattern is df[rows, columns]. This is a guide for reading the syntax, not a line to run.

Leaving the row position empty means “all rows.”

11 Select rows and columns

The code 1:5 creates the sequence 1, 2, 3, 4, 5.

1:5
[1] 1 2 3 4 5

Use that sequence before the comma to select the first five rows:

df[1:5, ]

Select the first five rows from one named column:

df[1:5, "col_a"]

Select a range of columns:

df[, 1:3]

The sample data frame has five columns. Select its last two columns with:

df[, 4:5]

Select nonconsecutive columns by combining their positions:

df[, c(1, 4, 5)]

Save the selected columns as a new object:

df2 <- df[, c(1, 4, 5)]
df2

11.1 Create a sequence of odd row numbers

nrow() returns the number of rows in a data frame. The imported object df has 10 rows.

nrow(df)
[1] 10

seq() creates a sequence. Here it begins at 1, ends at the last row, and moves by 2:

odd_rows <- seq(from = 1, to = nrow(df), by = 2)
odd_rows
[1] 1 3 5 7 9

Use odd_rows before the comma to select those rows:

df[odd_rows, ]

12 Calculate descriptive statistics

Create a short numeric vector so the input and output are easy to see:

scores <- c(72, 88, 81, 94)
scores

Then run each descriptive function:

mean(scores)
median(scores)
sd(scores)
var(scores)
[1] 83.75
[1] 84.5
[1] 9.394147
[1] 88.25
Function Result it calculates
mean() average
median() middle value
sd() standard deviation
var() variance

Use the same functions with a data-frame column:

mean(df$col_a)
median(df$col_a)
sd(df$col_a)
var(df$col_a)

Try it yourself

Repeat the same four functions with col_b and col_c. Type every line so the pattern becomes familiar:

mean(df$col_b)
median(df$col_b)
sd(df$col_b)
var(df$col_b)

mean(df$col_c)
median(df$col_c)
sd(df$col_c)
var(df$col_c)

12.1 Missing values

NA is R’s marker for a missing value.

scores_with_missing <- c(80, 92, 75, 88, NA)
mean(scores_with_missing)
[1] NA

Tell mean() to remove missing values for this calculation:

mean(scores_with_missing, na.rm = TRUE)
[1] 83.75

13 Create or replace a column

Assigning values to a new column name creates a column:

df$new_col <- c(5, 6, 7, 8, 9, 9, 8, 7, 6, 5)

Named indexing also creates a column:

df[, "new_col2"] <- c(5, 6, 7, 8, 9, 9, 8, 7, 6, 5)

Numeric indexing changes the column that already occupies that position:

df[, 2] <- c(5, 6, 7, 8, 9, 9, 8, 7, 6, 5)

The last line replaces column 2. It does not add a new column.

14 Group work

The mtcars practice is on a separate page so you can try each task before seeing more worked code. Keep this lesson open in one tab and use it whenever you need to review a pattern.

Open the Week 1 group work

15 Questions and troubleshooting

When a line does not work, bring these four pieces of information:

  1. The exact line of code you ran.
  2. The Console output or error message.
  3. What you expected the code to do.
  4. The object names, quotation marks, commas, and parentheses you already checked.

Use the remaining class time to complete the Week 1 group work and ask questions as they come up.

16 Week 1 reference

Task Code pattern
Check the Project location getwd()
Manually change the working directory setwd("full/path/to/folder")
Save a value name <- value
Combine values c(value1, value2)
Import a CSV read.csv("data/file.csv")
Print an entire object df
Inspect a data frame head(), names(), str(), class()
Inspect every column type sapply(df, class)
Select one named column df$column
Select rows and columns df[rows, columns]
Calculate an average mean(vector)
Remove missing values mean(vector, na.rm = TRUE)
Open Help ?function_name