R Basic Operations
Before You Start
- How do I import and export data? What if I have multiple data files to read?
- How do I add or remove a column or row?
- How do I convert variables from numeric to factor?
Basic Procedure
Import Dataset
From the menu, File > Import Dataset:

Or from the Environment pane, Import Dataset:

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 aforloop. 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())
- Run it and it gives you the path:
- 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.Rprojfile) 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
- When to use: The working directory is where R reads and saves files by default.
- Functions:
getwd(),setwd() - Comment: This is very useful when you combine it with statements, such as reading multiple files.
- Resources: R-bloggers: Get and set working directory (setwd / getwd) in R
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 thecol_*()functions, e.g.read_csv("data.csv", col_types = cols(ID = col_character()))
- haven package:
- 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 aforloop (see Syntax Sample) - purrr package:
combined_data <- map_dfr(c("A.csv", "B.csv"), ~ read_csv(.x) %>% mutate(file = .x))
- readr package:
- Comment: I don’t suggest
lapply()orforstatements 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), thenwrite_xlsx(df, "data.xlsx"). - Functions:
- Base R:
write.csv(data, file = "data.csv", row.names = FALSE) - readr package:
write_csv(data, "data.csv")
- Base R:
- 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 |
|
You want to see each variable’s data type and decide whether to convert it. Read more: Statology: How to use str() function in R |
Convert to numeric |
|
Create dummy variables, or convert factors to numbers after importing a csv file. When you use Read more: RDocumentation: numeric, Data Wrangling Recipes in R: Numeric/integer variables |
Convert to 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 |
|
Convert numbers into Read more: RDocumentation: logical, Data Wrangling Recipes in R: Logical variables |
Convert to 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 |
|
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 |
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. Read more: readr: Introduction |
Subset Selection and Modification
Remove rows
- Variable types: All
- When to use: You no longer need one participant’s data.
- Functions:
- Remove the second row:
data[-2, ] - Base R:
subset() - dplyr package:
filter()
- Remove the second row:
- Comment:
-and!mean “delete”. Insidedata[rows, columns], the,separates rows from columns, and leaving one side empty means all rows or all columns. - Resources: FavTutor: Remove row in R, Displayr: How to remove a row or column from a table using R
Remove columns (variables)
- Variable types: All
- When to use: You no longer need a column.
- Functions:
- By name:
data[, !names(data) %in% "variable"] - Remove the first column:
data[, -1] - Base R:
subset() - dplyr package:
select(-variable)
- By name:
- Comment: As with rows,
-and!mean “delete”, and leaving one side of the,empty means all rows or all columns. - Resources: ListenData: Select or remove columns from data frame, Spark By Examples: How to remove column in R
Subset selection
- Variable types: All
- When to use: Select part of the raw data frame.
- Functions:
- Base R:
subset() - Remove the second row and the first column:
data[-2, -1]
- Base R:
- Comment: You can take subsets of vectors, matrices, data frames, and lists, but selecting rows and columns of data frames is what we do most. Mastering
filter()andselect()is enough. - Resources: Stack Overflow: How to subset rows and columns in R, RDocumentation: subset, Advanced R: Subsetting
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))
- dplyr package:
- 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()
- dplyr package:
- 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, whilefilter()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, ordata$`Variable 1`if the name contains a space - dplyr package:
pull()
- Base R:
- 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)
- Base R:
- 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 + Mon 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()
- Citation for R:
- 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()
- Remove one object:
Reduce function calls with do.call()
- Variable types: All
- When to use: Merge multiple data frames, or avoid writing out the same function call many times.
- Functions:
do.call() - Comment:
do.call()calls another function dynamically and passes it a list of arguments, e.g.do.call(rbind, data_list)stacks every data frame in a list. - Resources: Stack Overflow: What’s the difference between lapply and do.call?, Steve’s Data Tips and Tricks: The do.call() function in R
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()
- tibble package:
- 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()
- Base R:
- Comment:
sort()handles only one vector, whilearrange()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()
- stringr package:
- 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
- Variable types: Categorical
- When to use: You are not satisfied with the order of factor levels: e.g. in a figure you want the frequencies ordered from largest to smallest, or in a logistic regression you want a specific level as the reference group.
- Functions: forcats package: the
fct_*()functions, e.g.fct_infreq()(order by frequency) andfct_relevel()(set the reference level) - Resources: forcats: Introduction, R for Data Science (1st edition): Factors, R Programming: Zero to Pro: Character vectors, factors & ordered 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()
- Base R:
- 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(), andtail()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()
- tidyr package, long to wide:
- 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
- Variable types: All
- When to use: You want all data from both datasets and don’t want to drop anything. The combined data frame will have IDs 1, 2, 3, 4, 5.
- Functions:
full_join() - Comment: This keeps all data, and any missing information is filled with NA.
- Resources: dplyr: Mutating joins, RDocumentation: plyr join, R for Data Science: Joins
Merge two data frames, keeping only the overlapping rows
- Variable types: All
- When to use: You want the participants whose IDs appear in both datasets. The combined data frame will have IDs 1, 2, 3.
- Functions:
inner_join() - Comment: Only keeps the observations that match in the reference column.
- Resources: dplyr: Mutating joins, RDocumentation: plyr join, R for Data Science: Joins
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, andanti_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
- Variable types: All
- When to use: Combine two different data frames.
- Functions:
merge() - Comment:
merge()is more flexible but more complicated. - Resources: RDocumentation: merge, An Introduction to R for Research: Merge (join)
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
- R for Data Science (1st edition): Import, Tidy, Transform, Visualize, and Model Data
- R Cookbook, 2nd Edition: Data Structures
Further Study
Recommended classes or training