R Basic Operations

Before You Start

  1. How do I import and export data? What if I have multiple data files to read?
  2. How do I add or remove a column or row?
  3. How do I convert variables from numeric to factor?

Basic Procedure

Import Dataset

From the menu, File > Import Dataset:

Import Dataset

Or from the Environment pane, Import Dataset:

Environment

Useful Packages: Tidyverse

Tidyverse makes R much less painful. It is a collection of packages with utility functions that we will use a lot for data processing.

  • readr: Read and import data based on specific conditions. You can read more in R for Data Science: Data import.
  • dplyr: Process rows or columns, for example selecting specific columns or renaming a column.
  • tibble: A modern way of creating data frames.
  • stringr: Handle character variables (everything you can imagine). For example: calculating the length of a string; adding, removing, and modifying spaces; sorting; counting; case conversion; and detecting, locating, extracting, matching, replacing, and splitting. It is very useful for batch processing variable names in quantitative research.
  • purrr: Mainly provides the map() functions, which are more concise and effective than a for loop. They are useful when you repeat the same operation many times, but we will leave them for the Statement section.
  • forcats: Sort, filter, and combine factors (categorical variables).

Summary and Practice

The cells in this section run in your browser on the simulated dataset described in Example Data. Edit the code and run it; the first cell loads the packages and the data.

Find Path

Find a file path

  • When to use: You want to import a data file. file.choose() opens a file browser and gives you the path, which you can copy into a read function.
  • Functions:
    • Run it and it gives you the path: file.choose()
    • Combine them together: read_sav(file.choose())
  • Comment: Use / instead of \ when you type a path by hand.
  • Resources: RDocumentation: file.choose

Build a file path with here

  • When to use: You know a file’s name and where it sits inside your project folder, and want a path that works on any computer.
  • Functions: here package: here("data", "file.csv")
  • Comment: here() does not search for the file. It joins your project root (the folder with your .Rproj file) with the names you give it, so the same script runs on any computer without changing paths.
  • Resources: here: Introduction

Get or set the working directory

Import and Export Dataset

Import a dataset

  • When to use: Read data (or multiple datasets), data from a remote path, specific columns, etc.
  • Functions:
    • haven package: read_sav()
    • Base R: read.csv()
    • readr package: read_csv(); to specify variable types, use the col_*() functions, e.g. read_csv("data.csv", col_types = cols(ID = col_character()))
  • Comment: I recommend importing a csv file instead of a sav file to avoid possible errors: haven reads the SPSS labels, which can cause issues. read_csv() is faster and does not convert strings to factors. It also gives you many ways to read specific files.
  • Resources: haven: read_spss, readr: read_delim, R for Data Science: Data import

Read multiple datasets

  • When to use: Read several files and stack them vertically into one data frame, with the file name stored in a first column called Name. If you want to keep the result in the environment, remember to assign it to an object.
  • Functions:
    • readr package: data <- read_csv(c("A.csv", "B.csv"), id = "Name")
    • Base R: lapply() or a for loop (see Syntax Sample)
    • purrr package: combined_data <- map_dfr(c("A.csv", "B.csv"), ~ read_csv(.x) %>% mutate(file = .x))
  • Comment: I don’t suggest lapply() or for statements if you are a beginner. Their logic is to go through the whole folder, reading each path and file name in turn.
  • Resources: Stack Overflow: Add filename column to table as multiple files are read and bound

Export data

  • Variable types: All
  • When to use: Export your data. Here I only list csv files, but you can also export an Excel file with the writexl package: library(writexl), then write_xlsx(df, "data.xlsx").
  • Functions:
    • Base R: write.csv(data, file = "data.csv", row.names = FALSE)
    • readr package: write_csv(data, "data.csv")
  • Comment: As with importing, you have a number of options when you export (check the function documentation for details). write_csv() runs fast.
  • Resources: rdrr.io: write.table, readr: write_delim

Convert Variable Types

These functions work on variables of any type.

Task Function When to use

Check data types

str()

You want to see each variable’s data type and decide whether to convert it. str() shows the type of a list, object, vector, or column.

Read more: Statology: How to use str() function in R

Convert to numeric

as.numeric(x, ...)

Create dummy variables, or convert factors to numbers after importing a csv file.

When you use as.numeric() on a factor, R returns the internal integer code of each level, not the level itself. Use as.numeric(as.character(x)) instead (see the code below this table).

Read more: RDocumentation: numeric, Data Wrangling Recipes in R: Numeric/integer variables

Convert to character

as.character()

Convert numbers or logical values into text, e.g. participant IDs that should be treated as labels rather than numbers.

Read more: RDocumentation: character

Convert to logical

as.logical()

Convert numbers into TRUE/FALSE: 0 becomes FALSE and any non-zero number becomes TRUE. In the other direction, as.numeric() turns TRUE into 1 and FALSE into 0.

Read more: RDocumentation: logical, Data Wrangling Recipes in R: Logical variables

Convert to factor

as.factor()

Display levels instead of numbers in the value column.

Read more: RDocumentation: factor, Data Wrangling Recipes in R: Factor/categorical variables

Convert to date

as.Date(), format(), as.POSIXct(), as.POSIXlt()

Convert a string of numbers or characters into a date or time.

Read more: Data Wrangling Recipes in R: Date/time variables, Stat2Labs: Introduction to working with dates in R

Convert a character vector into a more specific type

readr package: the parse_*() functions, e.g. parse_number(), parse_date()

You want to convert a character variable to the appropriate type (date, factor, logical, double, integer, etc.).

These functions are very useful in data cleaning, as long as your data follows a specific pattern. parse_number() extracts the number from a string that contains non-numeric characters.

Read more: readr: Introduction

Subset Selection and Modification

Remove rows

Remove columns (variables)

Subset selection

Add, modify, or delete columns

  • When to use: Add two columns holding the mean and the z-score. You can also delete a column by setting it to NULL.
  • Functions: dplyr package: mutate(data, new_column = ...)
  • Comment: You can add several columns in one mutate() call, and a new column can be a vector, the result of a function, or a single value. mutate() is useful together with statements or other functions.
  • Resources: dplyr: mutate

Select specific columns

  • When to use: select() can be combined with other functions, statements, or conditions to pick the columns you want.
  • Functions: select()
  • Comment: Combined with other conditions, you can also choose variables by naming pattern, such as variables whose names start with certain letters.
  • Resources: dplyr: select

Select columns by name pattern

  • Variable types: All
  • When to use: Extract the variables that start with “A”, end with “C”, and contain “b”.
  • Functions:
    • dplyr package: starts_with(), ends_with(), contains(), everything()
    • Base R, keep only the leading letters of each column name: gsub("[^A-Za-z]+.*", "", colnames(df))
  • Comment: These conditions can be combined with &, |, !, etc.
  • Resources: dplyr: select

Select specific rows

  • Variable types: All
  • When to use: Choose rows based on column values, or split the data frame.
  • Functions:
    • dplyr package: filter()
    • Index rows by their (integer) positions: slice()
  • Comment: filter() keeps the rows that meet a condition written with ==, >, etc. slice() can’t delete or replace rows directly, but you can do it by selecting the rows you want and saving them as a new data frame. slice() works by position, while filter() works by content (conditions).
  • Resources: dplyr: filter, dplyr: slice

Keep only unique/distinct rows

  • Variable types: All
  • When to use: You only want unique participant data (removing duplicates), or you are looking for outliers.
  • Functions: distinct(), unique()
  • Comment: These two functions are very useful in data cleaning, especially unique(), which you can combine with a loop.
  • Resources: dplyr: distinct, rdrr.io: unique

Extract a specific variable or column

  • Variable types: All
  • When to use: You want only one variable (column) instead of the entire data frame.
  • Functions:
    • Base R: data$Variable, or data$`Variable 1` if the name contains a space
    • dplyr package: pull()
  • Comment: Be careful how you name variables: avoid spaces and special characters such as -. If a name has them, wrap it in backticks.
  • Resources: dplyr: pull

Data Frames and Essential RStudio Operations

Create an object

  • Functions: <-
  • Comment: From the start, get into the good habit of saving the result of every processing step as an object in the environment.

Display an object

  • When to use: You want to see your results, data, list, etc.
  • Functions: print(), or just run the object’s name (e.g. data)
  • Comment: In RStudio you can run code line by line, and you can select just an object’s name and run it to see its contents.

List all the variables

  • Variable types: All
  • When to use: Find out what variables your data frame contains.
  • Functions:
    • Base R: names(data), colnames(data), str(data), ls(data)
    • dplyr package: glimpse(data)
  • Resources: dplyr: glimpse

Pipe an object forward into a function

  • When to use: In multi-step operations, pass the result of one step to the next function to keep the syntax concise.
  • Functions: magrittr package (loaded with tidyverse): %>%
  • Comment: The shortcut is Ctrl + Shift + M (Cmd + Shift + M on Mac). You will use it very often.
  • Resources: magrittr: pipe, Pipe baking animation (GIF)

Check the R version or cite R

  • When to use: You want to cite R or RStudio in your paper.
  • Functions:
    • Citation for R: citation()
    • R version: R.version.string
    • RStudio version: RStudio.Version()
  • Resources: Posit Support: Citing RStudio

Save R objects

  • When to use: Save objects, or the whole working environment, so that you can return to the same state later.
  • Functions: save(), save.image()
  • Resources: RDocumentation: save

Clean the environment

  • When to use: Your memory is running low, or you no longer need the objects in the environment.
  • Functions: Remove everything: rm(list = ls())
  • Comment: Use rm(list = ls()) carefully. You can also click the broom icon at the top of the Environment pane.

List or remove objects

  • Functions:
    • Remove one object: rm()
    • List objects: ls()

Reduce function calls with do.call()

Another type of data frame: tibble

  • Variable types: All
  • When to use: You want a data frame that prints and behaves more nicely.
  • Functions:
    • tibble package: tibble()
    • Coerce objects into tibbles: as_tibble()
  • Comment: A tibble does not support row names and encourages using columns as unique identifiers. It also prints and displays better.
  • Resources: tibble: tibble

Reorder columns

  • Variable types: All
  • When to use: Put the participant ID in the first column.
  • Functions: dplyr package: relocate(), select()
  • Comment: relocate() is cleaner and simpler, and it doesn’t change the structure of the data. select() has more functionality.
  • Resources: dplyr: relocate, dplyr: select

Reorder rows

  • Variable types: Continuous
  • When to use: Sort the rows of the data frame in ascending or descending order of one or more columns.
  • Functions:
    • Base R: data[order(data$age), ]; sort() sorts a single vector
    • dplyr package: arrange(); descending order: desc()
  • Comment: sort() handles only one vector, while arrange() reorders the rows of a data frame and accepts several conditions, e.g. age in ascending order and then depression level in descending order: arrange(data, age, desc(depression)).
  • Resources: rdrr.io: order, rdrr.io: sort, dplyr: arrange, dplyr: desc

Data Cleaning Preparation

Detect, locate, extract, match, replace, and split characters

  • Variable types: Character
  • When to use: Pick the variables whose names share the same first three letters; replace specific letters.
  • Functions:
    • stringr package: str_detect(), str_extract(), str_replace(), str_split()
    • Base R: grep(), grepl(), sub(), gsub()
  • Comment: Processing characters is a big topic, so learn the functions when you actually clean or process data. Modern programming languages are very flexible at handling characters: don’t handle them manually if you can; use statements or scripts instead.
  • Resources: stringr: Introduction, rdrr.io: grep, R Programming for Data Science: Regular expressions, R for Data Science (1st edition): Strings

Sort, filter, and combine factors

Check your data

  • When to use: Check that data entry and import are correct.
  • Functions:
    • Base R: summary()
    • dplyr package: slice(); randomly select rows: slice_sample()
    • First or last few rows: head(), tail()
  • Comment: summary() gives detailed information about each variable: minimum, first quartile, median, mean, third quartile, and maximum for numeric variables, and frequencies for each factor level. slice(), head(), and tail() let you look at the raw data directly.
  • Resources: dplyr: slice

Rename variables

  • Variable types: All
  • When to use: Change a variable name from “score” to “total_score”.
  • Functions: dplyr package: rename(data, total_score = score)
  • Resources: dplyr: rename

Reshape data: wide to long, or long to wide

  • Variable types: All
  • When to use: Typically each column is one variable (“ID, Variable 1, Variable 2, …”), but sometimes you need several variables stacked into one column and sorted by ID (e.g. for a figure).
  • Functions:
    • tidyr package, long to wide: pivot_wider()
    • tidyr package, wide to long: pivot_longer()
  • Resources: tidyr: pivot_wider, tidyr: pivot_longer

Combine Data Frames, Rows, and Columns

The join examples below use two data frames: data1 with IDs 1, 2, 3, 4 and data2 with IDs 1, 2, 3, 5.

Stack data frames vertically (add rows)

  • Variable types: All
  • When to use: Add more participants’ data to the raw data frame.
  • Functions: dplyr package: bind_rows(); Base R: rbind()
  • Resources: dplyr: bind_rows

Combine data frames side by side (add columns)

  • Variable types: All
  • When to use: Add more columns or variables.
  • Functions: dplyr package: bind_cols(); Base R: cbind()
  • Comment: Rows are matched by position, not by ID, so both data frames must have the same participants in the same order. To match by ID, use a join (below).
  • Resources: dplyr: bind_cols

Merge two data frames by ID, keeping one side

  • Variable types: All
  • When to use: Add more variables to the raw data frame. If data1 and data2 share (some) IDs, you can merge the remaining columns using the IDs of data1 or data2 as the baseline.
  • Functions: dplyr package: left_join(data1, data2, by = "ID"), right_join(data1, data2, by = "ID")
  • Comment: When the IDs do not fully match, left or right decides whose IDs you keep. With left_join(), the result keeps only IDs 1, 2, 3, 4, and for ID 4 the variables from data2 will be NA.
  • Resources: dplyr: Mutating joins, RDocumentation: plyr join, R for Data Science: Joins

Merge all data from both data frames

Merge two data frames, keeping only the overlapping rows

Filter one data frame by another

  • Variable types: All
  • When to use: Use data2 as a reference to keep or drop rows of data1. The result has only the columns of data1 and nothing from data2: semi_join() keeps IDs 1, 2, 3, and anti_join() keeps ID 4.
  • Functions: semi_join(), anti_join()
  • Comment: Similar to filter(): it filters your original data frame and does not add anything (columns or rows) from the reference data frame.
  • Resources: dplyr: Filtering joins, RDocumentation: plyr join, R for Data Science: Joins

Merge data frames in different ways

List all combinations of conditions

  • Variable types: All
  • When to use: In a multifactorial experimental design (e.g. 2x2), list all possible combinations of conditions.
  • Functions: cross_join()
  • Comment: It combines each row of one data frame with each row of another to produce all possible combinations of rows, which is handy when designing psychology experiments.
  • Resources: Statology: How to do a cross join in R, dplyr: cross_join

Syntax Sample

Read files on your computer

These examples read files from your own computer, so run them in RStudio.

library(tidyverse)  # readr, dplyr, tidyr, stringr, forcats, purrr
library(haven)      # read_sav()

# Read an SPSS .sav file
dataraw <- read_sav("C:\\Users\\Desktop\\data.sav") # note: use \\ or / instead of \

# List all csv files
csv_files <- list.files(path = "put your path here", pattern = "\\.csv$", full.names = TRUE)

# Read multiple csv files in a folder
folder_path <- "path/to/your/folder"
file_list <- list.files(path = folder_path, pattern = "\\.csv$", full.names = TRUE) # create a file_list
data_list <- lapply(file_list, read.csv) # read all csv files on the file_list
combined_data <- do.call(rbind, data_list) # combine all data frames together

# Read multiple different files in a folder
library(readxl)  # Load the readxl package for reading .xlsx files

# Use the working directory as the folder path
folder_path <- getwd()

# List all files in the specified folder, including full paths
file_list <- list.files(path = folder_path, full.names = TRUE)

# Use lapply to read each file based on its extension
data_list <- lapply(file_list, function(file) {
  # Check if the file is a .csv file and read it as a data frame
  if (grepl("\\.csv$", file)) {
    read.csv(file)  # Read .csv file
  } else if (grepl("\\.txt$", file)) {
    read.table(file)  # Read .txt file
  } else if (grepl("\\.xlsx$", file)) {
    readxl::read_excel(file)  # Read .xlsx file
  # If the file extension is not recognized, return NULL
  } else {
    NULL
  }
})
# Optionally, remove NULL entries from the list
data_list <- Filter(Negate(is.null), data_list)

Assignment

It doesn’t matter if the code is neat and pretty, as long as you get there in the end!

  • Import data as a data frame or tibble. Export the dataset as a csv file.
  • Combine multiple files into one big data frame.
  • Convert the factor variable into numeric.
  • Check the data frame; pull out the first 3 and last 5 rows as a data frame.
  • Add a new column and name it “Mean”; add a new row and set its values to NA.
  • Delete the first column, and remove the last row.

Functions Required to Know How to Use

Write down what they can do and practice using them.

file.choose(), here(), read_csv(), write_csv(), ls(), arrange(), summary(), <-, %>%, str(), mutate(), as.factor(), as.numeric(), filter(), select(), starts_with(), unique(), bind_rows(), bind_cols()

Resources & References

Further Study

Recommended classes or training