7  Recap and getting data into R

7.1 Where you are now

The previous six chapters introduced R from the ground up. You have not yet analyzed any real data, and that is intentional: most of the difficulty new users encounter with R is not statistical but environmental. People struggle not because regression is hard but because they cannot tell the difference between an R script and an R project, or because they do not realize an R session can silently inherit state from yesterday. By the end of Section 1, those obstacles are behind you.

This chapter has three purposes. The first is to recap the six earlier chapters in compact form. The second is to introduce one practical step that Section 1 has not yet covered: how to load data from a file into R. The third is to point you toward what comes next. The questions at the end consolidate concepts across all six earlier chapters and the new material on data import.

7.2 What you have learned

Chapter 1 introduced R and the case for working with code. R is a free, open-source programming language designed for statistics. The reasons to use it rather than SPSS or Excel are reproducibility (the script is a complete record of what you did), error detection (every step is inspectable), and scaling (operations defined once can be applied to many variables). R is “object-based” in the sense that almost everything you work with is a named object, created by you, that can be passed into functions to produce new objects.

Chapter 2 distinguished R the engine from RStudio the dashboard. R performs the computations; RStudio provides the working environment around it. You install both, and the standard environment for new users is RStudio Desktop (Open Source Edition). Alternatives exist (Positron, VS Code with the R extension, Jupyter), but RStudio remains the easiest entry point.

Chapter 3 mapped out the relevant kinds of files and one in-memory state. The environment holds your objects while R is running and disappears when R closes. An R script (.R) is a saved record of code. An RData file (.RData) is a saved snapshot of objects. An R project (.Rproj) is a folder formally designated as a project, which sets the working directory and groups related files. R Markdown (.Rmd) files mix prose and code to produce finished documents. The script is the authoritative record; everything else is for convenience or for reporting.

Chapter 4 examined R sessions and how they relate to projects. A session is one running instance of R; opening a project starts a session, closing or restarting the session destroys the in-memory state. The recommended habit is to restart the session frequently and re-run the script from the top, so that no object exists in the environment for reasons other than your script. The corresponding RStudio settings (“Restore .RData into workspace at startup” and “Save workspace to .RData on exit”) should be turned off, because they silently preserve state across sessions in a way that obscures bugs.

Chapter 5 introduced the main object types: single values (numbers, strings, logicals), vectors (ordered sequences of values of the same type), and data frames (rows are observations, columns are variables, each column a vector). It introduced the indexing rules, including 1-based indexing, the $ for column extraction, and the [rows, columns] two-dimensional bracket form. It also introduced functions: pieces of R that take objects as input and return objects as output, with a small toolkit (class, length, str, head, summary, nrow, ncol, colnames) that you will use to inspect almost any unfamiliar object.

Chapter 6 covered the basic operations of arithmetic and summary statistics, gave a first illustration of writing a custom function (with if and else), and worked through a substantive example in which a survey dataset with many distorted variables was corrected three ways: manually, with a function applied repeatedly, and with a function applied to all variables in one line. The third approach is the one that pays off in practice. The chapter ended with packages: how to install them, how to load them, how to find documentation, with psych::describe() and psych::describeBy() as concrete examples, and the :: notation as an alternative to loading.

7.3 What this means for the rest of the book

You now have everything you need to start using R for actual data analysis. Section 1 has covered the foundational half of Pillar 4 (the coding, programming, and communicating pillar introduced in the preface): how R works, how to set up a project, what objects and functions are, and how to install and use packages. The remaining sections turn to the other three pillars and to the second half of Pillar 4. Section 2 develops the data-manipulation skills that turn raw files into something you can analyze. Section 3 covers Pillar 1 (statistical modeling). Section 4 and the first part of Section 5 cover Pillar 2 (statistical inference). The middle and later chapters of Section 5 cover the visualization and reporting skills that complete Pillar 4. Section 6 covers Pillar 3 (causal inference). Where Section 1 was about setting up the environment, the remaining sections will be about doing things with it.

Two pieces of advice for the transition.

The first is that you should expect to consult the help system constantly. Even researchers with decades of R experience read help pages routinely. The skill that distinguishes someone fluent in R is not memorizing every function but knowing how to find the right one.

The second is that the workflow you have learned (project, restart, script, save explicitly when needed) is more important than any specific analysis you will run later. Statistical operations come and go; methods evolve; specific R functions are sometimes superseded by better ones. The discipline of organizing a project, restarting cleanly, and writing a script that reproduces an analysis from start to finish will serve you regardless of which analyses you eventually run.

7.4 A final missing piece: getting data into R

There is one practical step we have not yet covered. You know how to create objects from scratch, but in actual research projects your data does not arrive in your R script as hand-typed vectors; it arrives as a file on your computer, exported from a survey platform, an experimental software, a spreadsheet a collaborator sent you, or a database. Before you can analyze it, you have to load it into R.

This section covers the most common cases: comma-separated values (CSV) files, Excel files, and the point-and-click import feature in RStudio. We then return to the same comparison the rest of Section 1 has been building toward: code-based imports versus click-based imports, and why the code-based approach is the one to make your default.

For all the examples below, we assume you are working inside an R project (Chapter 4), so that the working directory is set to the project folder and you can refer to data files by paths relative to that folder. A common convention is to place data files in a subfolder called data inside the project, so that paths look like "data/survey_2024.csv".

7.4.1 Reading CSV files

A CSV file is a plain-text file in which rows of a table are stored as lines, and columns are separated by commas. CSV is the most common format for sharing tabular data because it is human-readable, software-agnostic, and supported by every statistical tool.

Base R has the function read.csv() for this:

survey <- read.csv("data/survey_2024.csv")

After this line, survey is a data frame with the contents of the file. You can inspect it with head(survey), str(survey), or summary(survey) as introduced in Chapter 5.

Three practical points about CSV files.

The first point is the separator. The “C” in CSV stands for “comma,” but in many European locales (including Austria, Germany, France) the convention is to use a semicolon instead, because the comma is already used as the decimal separator. If you open a CSV with read.csv() and the entire file ends up in a single column, the separator is probably a semicolon. Use read.csv2() instead, which assumes semicolon separators and comma decimals:

survey <- read.csv2("data/survey_2024.csv")

Or pass the separator explicitly to read.csv():

survey <- read.csv("data/survey_2024.csv", sep = ";", dec = ",")

The second point is the header row. By default, read.csv() assumes the first line of the file contains the column names. If your file has no header row, set header = FALSE.

The third point is alternatives in packages. The readr package (part of the tidyverse) provides read_csv(), which is faster on large files and gives clearer messages about how each column was interpreted. It returns a slightly different object (a “tibble,” which is a data frame with a few cosmetic differences). For Section 1 the base R read.csv() is sufficient.

7.4.2 Reading Excel files

Excel files have the extension .xlsx (modern Excel) or .xls (older Excel). Base R does not include a function to read them, so you need a package. The standard choice is readxl:

install.packages("readxl")  # only once, per computer
library(readxl)

survey <- read_excel("data/survey_2024.xlsx")

read_excel() handles both .xlsx and .xls. By default it reads the first sheet of the workbook. To read a specific sheet:

survey <- read_excel("data/survey_2024.xlsx", sheet = "responses")

The argument sheet accepts either the sheet name as a string or its position as a number (sheet = 2 for the second sheet).

Two notes worth flagging.

First, Excel files often contain things that do not translate well to a data frame: merged cells, formatting, formulas, multiple tables on one sheet, headers spanning several rows. If your Excel file is structured cleanly (one table per sheet, one header row, one variable per column), read_excel() works without further argument. If it is not, you may need to use range = "A3:F50" or similar to specify which cells to read. When you have control over the file, exporting it as a CSV first usually saves time.

Second, readxl reads from Excel files without needing Excel installed. The package parses the file format directly. This is a real advantage on machines that do not have Microsoft Office.

7.4.3 Point-and-click import in RStudio

RStudio includes a graphical import feature that handles both CSV and Excel files. To use it, click in the Files panel on the file you want to import, or go to File > Import Dataset in the menu and choose “From Text (base),” “From Text (readr),” or “From Excel.”

A dialog opens. It shows a preview of the data, lets you adjust options (delimiter, decimal separator, sheet for Excel files, header row, column types), and previews the result.

This is genuinely useful for one important reason: at the bottom of the dialog there is a Code Preview box that shows the R code corresponding to your current settings. Once you have the preview looking right, you can copy that code and paste it into your script.

If you simply click “Import,” the code runs once and the data appears, but the code is not added to your script. You will not be able to reproduce the import without going through the dialog again. The good practice is to use the dialog as a way to generate the code, copy it into your script, and then close the dialog.

7.4.4 Why coding the import is better

The reason to put the import in your script is the same reason to put any other step in your script. We have made this argument repeatedly in Section 1; in the context of data import it has four specific consequences.

The first is reproducibility. The import is the very first step of any analysis. If the import is in your script, then re-running the script from a clean session loads the data automatically; you do not need to remember which menu options you chose. If the import is not in your script, then your analysis is not reproducible: a colleague running your script will get an error on the very first line, because their environment does not contain the data.

The second is transparency. Reading read.csv("data/survey_2024.csv") tells the reader exactly which file is being loaded, with which separator, with which decimal convention. A click-through history tells nobody anything.

The third is portability. A scripted import using a relative path ("data/survey_2024.csv", not "C:/Users/yourname/Downloads/.../survey_2024.csv") works on any computer that has the project folder. You can email the project folder to a collaborator, or push it to a repository, and the same script will run.

The fourth is error correction. If the file’s structure changes (a new column is added, a separator changes, the file is renamed), you adjust one line of code. With a click-through workflow, you redo the entire dialog walkthrough, hoping to remember every setting you previously chose.

Use the import dialog as a helper that produces the code, then keep the code. The dialog is a good way to discover the right arguments for an unfamiliar file format; it is not a substitute for the script.

7.4.5 A practical pattern

A typical first script in a project loads the data, inspects it, and assigns it to a clean object. For example:

library(readxl)

# Load the raw data
survey <- read_excel("data/survey_2024.xlsx", sheet = "responses")

# Inspect
str(survey)
head(survey)
summary(survey)

You now have everything you need to begin analyzing real data, and you have a script that any future reader (yourself, a collaborator, a reviewer) can run from start to finish.

7.5 Check your understanding

1. Which best describes the relationship between R and RStudio?

2. Which file type is the authoritative record of an analysis?

3. Why is restarting the R session a recommended habit?

4. How often do you need to call library(packagename)?

5. Which expression extracts the column age from a data frame called survey?

6. At what position is the first element of a vector in R?

7. If x is a numeric vector containing one NA, what does mean(x) return?

8. What is the main practical benefit of writing a custom function and applying it to many variables at once, rather than performing the operation manually on each variable?

9. Which base R function reads a comma-separated values (CSV) file into a data frame?

10. You receive a CSV file from a European colleague. When you open it with read.csv(), the entire file ends up in a single column. What is the most likely cause and fix?

11. What is the recommended way to use RStudio’s “Import Dataset” dialog?