insurancedata <- read.csv("data/insurance.csv")10 Import Data Once
How to use readr, readxl, and haven
This chapter imports the team’s data into R once, the right way. Researchers re-read the import line they first ran in Coding a Plot, learn its three parts (object, function, file path), make a data folder inside the RStudio Project and import from it with the file name only, and inspect the result with head(), names(), nrow(), and ncol(). The Play imports the same data as a .csv and as an Excel file; the Lab imports the lab dataset, checks its variable names against the codebook in both directions with setdiff(), and recodes the special values (-99, -50) to NA, with Ref’s checks at every step. Your Turn gives the template for the team’s .cleandata file.
data import, csv, excel, SPSS, missing data
10.1 Introduction to Data Import
The first step of the data science workflow is to import your data: to bring a file from your project folder into R’s memory, as an object you can use. Public health researchers import data from many sources: survey platforms (Qualtrics, REDCap), spreadsheets (Excel, Google Sheets), other statistical software (SPSS, SAS, Stata), and R packages. In FRI Public Health, your team’s data comes from Qualtrics as an Excel file (Export Survey Data).
You have already imported data once. In Coding a Plot, the first line of code was:
insurancedata <- read.csv("data/insurance.csv")You watched it run without an explanation. Now you will read it, because every import you ever write has the same three parts.
10.2 📋 The Play
10.2.1 Play 1: Read the import line
| Part | What it is | What it does |
|---|---|---|
insurancedata |
the object name you choose | the labeled box that will hold the data (Coding a Plot) |
<- |
the assignment arrow (Coding a Plot) | “put what is on the right into the box on the left” |
read.csv( ) |
the function | reads a .csv file (comma-separated values, a plain-text spreadsheet) |
"data/insurance.csv" |
the function’s input: a file path in quotes | the folder data inside your project, then the file name, then its extension .csv |
Read it from right to left: open the file insurance.csv in the folder data, read it as a table, and call that table insurancedata. R looks for the data folder starting from your project folder, which is why the project matters (R Software). Nothing appears on the screen when this line runs. Look at the environment tab instead: insurancedata is there, with its number of rows (obs.) and columns (variables).
data folder in your project, once, and put every data file in it
Every import line in this playbook starts with "data/…". That path only works if there is a folder named data (lowercase, no space) inside your Lastname_FRI project folder, and the file is inside it. Neither exists until you make them:
- In RStudio, with your project open, go to the Files tab (bottom right) and click New Folder. Name it
dataand click OK. You do this once; the folder stays in your project. - Put the data file inside that folder, not next to it. Do this in Finder or File Explorer: open the project folder, open
data, and drag the file in (R Software shows the steps). - Check the Files tab: click
dataand you should see the file. Click the refresh icon at the top right of the tab if it does not appear.
If the code will not run: path does not exist means R could not find the file where the code says it is. Nine times out of ten the file is still in Downloads, or it is in the project folder but not inside data, or the folder is called Data or data files. Fix the folder, not the code. Keep lab_prep.R and your .qmd files in the project folder itself, next to Lastname_FRI.Rproj; only data goes in data.
10.2.2 Play 2: Look at what you imported
These are the same checks you ran in Coding a Plot, and you will run them on every dataset for the rest of the course. head() shows the first six rows. names() lists the variables. nrow() and ncol() count the people and the variables.
head(insurancedata) age sex bmi children smoker region charges
1 19 female 27.900 0 yes southwest 16884.924
2 18 male 33.770 1 no southeast 1725.552
3 28 male 33.000 3 no southeast 4449.462
4 33 male 22.705 0 no northwest 21984.471
5 32 male 28.880 0 no northwest 3866.855
6 31 female 25.740 0 no southeast 3756.622
names(insurancedata)[1] "age" "sex" "bmi" "children" "smoker" "region" "charges"
nrow(insurancedata) # how many people?[1] 1338
ncol(insurancedata) # how many variables?[1] 7
head() is also how you catch the two most common import problems at once. Every row should be one person (one respondent, with their own ResponseId), so a first row that is question text instead of a person means the file still has two header rows (Export Survey Data). And every column of numbers should be numbers, so values in quotes, or <chr> under a column name instead of <dbl>, mean a numeric column came in as text.
as.numeric()
R decides a column’s type from every value in it. If one person typed “twenty” in an age box, or a research assistant wrote a note in a cell of a scanner sheet, the whole column arrives as text (<chr>), and mean(), summary(), and every test will refuse it or give nonsense. The fix is as.numeric(), which turns every value that looks like a number into a number and every value that does not into NA, with a warning that says so:
as.numeric(c("322", "three hundred", "298", ""))[1] 322 NA 298 NA
Two rules when you use it. First, look before you convert: print the values that will become NA so you know what you are losing (filter(is.na(as.numeric(COLUMN)))). Second, count after: compare the number of NA values before and after, and report in Methods how many answers could not be used and why. In your own data, do this once, right after import, inside a mutate(): mutate(AGE = as.numeric(AGE)). The Lab practices it on a real scanner export, and Compare 2 Groups uses the same file.
Try it. Run head(insurancedata), then change it to head(insurancedata, 10) and to tail(insurancedata). The second input to head() is the number of rows; tail() shows the last rows instead of the first.
10.2.3 Play 3: Same play, Excel file
Your team’s data is an Excel file (.xlsx), not a .csv. The import line has the same three parts. Only the function changes, because the file type changed, and that function comes from the readxl package, so library(readxl) has to run first (R Packages).
library(readxl)
insurancedata_xl <- read_excel("data/insurance.xlsx")
head(insurancedata_xl)# A tibble: 6 × 7
age sex bmi children smoker region charges
<dbl> <chr> <dbl> <dbl> <chr> <chr> <dbl>
1 19 female 27.9 0 yes southwest 16885.
2 18 male 33.8 1 no southeast 1726.
3 28 male 33 3 no southeast 4449.
4 33 male 22.7 0 no northwest 21984.
5 32 male 28.9 0 no northwest 3867.
6 31 female 25.7 0 no southeast 3757.
Compare the two head() outputs. Same people, same variables, same numbers. The file type does not change the data; it only changes which function reads it. (read_excel() prints the output as a tibble, which shows the number of rows and the type of each column, such as <dbl> for numbers and <chr> for text, under the column names. That extra line is useful, not a problem.)
For your team’s data, the line looks like this (Team 1, exported on the October 9 lecture; the object is named alldata because it holds every response, and later chapters filter it down):
alldata <- read_excel("data/10.09.2026.team1.cleandata.xlsx")An Excel file can hold several sheets. read_excel() reads the first sheet unless you say otherwise, and Excel names that sheet Sheet1 by default. Your .cleandata file has one sheet, and the lab file keeps its data on the first sheet, so in both cases the file name is enough. If you ever need a different sheet (the lab file also has a codebook sheet), add a second input, sheet =:
mh_codebook <- read_excel("data/ANTH306_LayConceptionsMH_SYNTHETIC.xlsx", sheet = "codebook").cleandata file, with the file name only
Your report imports your team’s .cleandata file (one header row, Export Survey Data) from the data folder of your project, using the path "data/…" and nothing else: no setwd(), no /Users/yourname/…. That is what makes the same code run on your teammates’ computers and your peer mentor and/or Dr. Shane’s.
The pattern holds for every file type: only the function changes. read_sav() from the haven package reads SPSS .sav files, read_csv() from readr (part of the tidyverse) is a faster read.csv(), and read_dta() reads Stata files. See the Posit data import cheatsheet.
10.3 🏈 The Lab
You watched the play above with example datasets. Now import the lab dataset yourself: a survey about what people believe about mental health. Everyone in the course uses the same file, so you can check your answers.
Ref’s kickoff. This lab is not graded, so I am here to help you check your own work. Try each step before you open my check. If your answer does not match, that is not a penalty. It is how you find out what to fix.
Two kinds of data files appear in this playbook, and they live in two different places.
Lab data (class Google Drive only). The lab dataset and everything that goes with it are not on the playbook website or in its GitHub repository. Get them from the Quant folder of the class Google Drive and put them where the chapter says: ANTH306_LayConceptionsMH_SYNTHETIC.xlsx and ANTH306_LayConceptionsMH_SYNTHETIC_LONG.xlsx in your project’s data folder, and lab_prep.R in the project folder itself (next to your .Rproj).
Play data (download from the playbook). Every file used in a Play is public and can be downloaded with the links below. Save each one into your project’s data folder. If a chapter’s Lab uses one of these files (Import Data Once, Lab Play 5, uses the Veggie Meter file), this is where to get it.
| File | Used in | Download |
|---|---|---|
insurance.csv |
Coding a Plot, Visualize a Comparison, Visualize a Relationship | download |
insurance.xlsx |
Import Data Once | download |
veggiescore_SYNTHETIC.xlsx |
Import Data Once (Lab Play 5), Compare 2 Groups | download |
foodsecurity_SYNTHETIC.xlsx |
Compare 2 Groups, Compare 1 Group Pre/Post | download |
health_status_data.csv |
Visualize a Comparison, Compare 2 Groups, Compare 3+ Groups, Visualize a Relationship, Shiny Data Viz | download |
safety_data.csv |
Relate 2 Variables, Relate 3+ Variables | download |
pregnancy_beliefs_SIMULATED.csv |
Relate 3+ Variables | download |
healthbeliefs_SELECT.csv |
Writing Functions in Methods and Results | download |
If a download link opens the file in your browser instead of saving it, right-click the link and choose Save Link As…. Your own team’s data file never comes from either place: it comes from your team’s Qualtrics export (Export Survey Data) and is shared only inside your team.
Before you start
- Download the lab data file,
ANTH306_LayConceptionsMH_SYNTHETIC.xlsx, from the class Google Drive. Put it in the data folder inside yourLastname_FRIproject folder (the Important box above shows how to make that folder if you have not yet). - From the same class Google Drive folder, download the short R script
lab_prep.R. Put it in yourLastname_FRIproject folder itself, next toLastname_FRI.Rproj(not inside data). You will not use it in this chapter; from Transforming Your Data on, every Lab starts by running it. - Open your RStudio Project and create
Lastname_lab2.qmd, your first lab file, with the load-library chunk at the top (Start a Report). Run that chunk. You needreadxl.
10.3.1 Lab Play 1: Import the data
The file has more than one sheet. The survey answers are on the first sheet, Sheet1, which is the one read_excel() reads by default. Import it and name the object mh_raw. Then find out how many rows (people) and columns (variables) it has.
library(readxl)
mh_raw <- read_excel("data/ANTH306_LayConceptionsMH_SYNTHETIC.xlsx")
nrow(mh_raw) # how many people?
ncol(mh_raw) # how many variables?10.3.2 Lab Play 2: View the variables
Look at the column names with names(), look at the first rows with head(), and get a summary of one variable, POLITICALBELIEFS, with summary(mh_raw$POLITICALBELIEFS).
10.3.3 Lab Play 3: Do the variable names match the survey?
This is the check that matters most. The column names in R come straight from the variable names that were typed into Qualtrics (Name and Recode Variables in Qualtrics). If a name is misspelled, or a question was never named, you will see it here first, and it is far cheaper to fix now than after you have written code around the wrong name.
For the lab dataset, the survey’s variable names are listed on the sheet called codebook, one row per variable. Import that sheet as mh_codebook, then compare its Variable column with names(mh_raw). Four things to look for:
- Names that are not names. Anything like
Q17,Q23_1, orQID9is a question that was never named in Qualtrics. It has to be named there and exported again, not renamed by hand in Excel. - Spelling and capitals.
STIGMA_PUB3andStigma_Pub3are two different variables to R. Watch for a stray space, a lowercase letter, or a typo (STIMGA). - Something missing. A variable the codebook lists that is not in the data usually means a question was deleted or was not exported (a Download all fields problem, Export Survey Data).
- Something extra. Columns in the data that the codebook does not list. Some are normal: Qualtrics adds housekeeping columns (
StartDate,Duration_sec,Progress), and a select-all question exports as one column per box (RACIALIZED_1,RACIALIZED_2, …) that a codebook often describes in a single row. Anything else extra needs an explanation.
Reading 134 names by eye is how you miss things, so let R do the comparison. setdiff(A, B) returns the items that are in A but not in B, so:
setdiff(names(mh_raw), mh_codebook$Variable)lists columns that are in the data but not in the codebook (checks 1, 2, and 4 above).setdiff(mh_codebook$Variable, names(mh_raw))lists variables that are in the codebook but not in the data (check 3, and the other half of check 2: a misspelled name shows up in both lists, once under each spelling).
If both lists come back empty, the names match exactly. Run both on the lab data.
names(mh_raw) # the VARIABLES in your dataset
head(mh_raw, 10) # the first 10 people
summary(mh_raw$POLITICALBELIEFS) # one variable: look at the minimum
mh_codebook <- read_excel("data/ANTH306_LayConceptionsMH_SYNTHETIC.xlsx",
sheet = "codebook")
# in the data but NOT in the codebook: unnamed questions, typos, extra columns
setdiff(names(mh_raw), mh_codebook$Variable)
# in the codebook but NOT in the data: missing or misspelled variables
setdiff(mh_codebook$Variable, names(mh_raw))10.3.4 Lab Play 4: Turn the missing codes into NA
Lab Play 2 found a minimum of -99 in POLITICALBELIEFS. In this survey, -99 means “Prefer not to say” and -50 means “Don’t know” (Name and Recode Variables in Qualtrics). If they stay as numbers, R will average them into every score. Replace both codes with NA, R’s word for missing, everywhere in the dataset, then run summary(mh_raw$POLITICALBELIEFS) again.
mh_raw[mh_raw == -99] <- NA # prefer not to say -> missing
mh_raw[mh_raw == -50] <- NA # don't know -> missing
summary(mh_raw$POLITICALBELIEFS)mh_raw == -99 finds every cell equal to -99, and <- NA writes NA into those cells. Transforming Your Data shows the tidyverse way to do the same thing, replace_with_na_all().
10.3.5 Lab Play 5: A number column that came in as text
The lab dataset came in clean, but most team datasets will not. veggiescore_SYNTHETIC.xlsx (download it into your data folder; it is a Play file, so it is not on the Google Drive) is a scanner export from an FRI Veggie Meter study in which VEGGIESCORE should be a number from about 100 to 800. Import it as veggiedata, run summary(veggiedata$VEGGIESCORE), and read the first line. Then find the values that are not numbers, convert the column with as.numeric() inside mutate(), and count how many values became NA.
veggiedata <- read_excel("data/veggiescore_SYNTHETIC.xlsx")
summary(veggiedata$VEGGIESCORE) # Class: character
veggiedata |> # look before you convert
filter(is.na(suppressWarnings(as.numeric(VEGGIESCORE))), !is.na(VEGGIESCORE)) |>
count(VEGGIESCORE)
veggiedata <- veggiedata |>
mutate(VEGGIESCORE = as.numeric(VEGGIESCORE)) # words become NA (R warns you)
summary(veggiedata$VEGGIESCORE) # 24 NA's; min and max are impossible values
nrow(veggiedata) # still 300suppressWarnings() in the look-first line only hides the “NAs introduced by coercion” warning while you are inspecting; leave the warning visible when you do the real conversion so that you notice it.
Ref’s final whistle. That is the end of the lab. Save your .qmd, render it, and back up your .qmd and .R files to the R Labs folder in your ELN before you quit RStudio.
10.4 🏆 Your Turn
SWAP means swap it for your own
Every Your Turn section gives you template code. Most of it is real code that you keep exactly as it is. The parts you must change are marked with one code word: SWAP.
- A word that starts with
SWAPis a placeholder:SWAPOUTCOME,SWAPGROUP_3CAT,SWAPFILE.xlsx,"SWAP: your title". Swap the whole word for your own variable, file, or words. What followsSWAPtells you what goes there, and any ending such as_3CATor_PREis part of the name you should keep. - A comment that starts with
# SWAP:tells you what to put in that line. - Everything else stays, even if it looks generic.
alldata,cleandata,mydata,my_keys,ttestmodel1, andplots/are real names the playbook uses on purpose.
When you are done, search your file for SWAP. If the word is still there, so is a placeholder.
After data collection ends and you have downloaded your team dataset, meet with a Quant Peer Mentor during lab before you go further. The quant PM lab schedule is in Column E of the “Student Lab Hours (ANTH306-f2026)” Google Sheet.
Once you finish all of the R Labs, come back here with your team’s .cleandata file. Your report uses exactly three names for your data, and this is where the first two are made:
| Name | What it is | Where it is made |
|---|---|---|
alldata |
The file exactly as you imported it. It is never changed, so you can always go back to it. | Here |
cleandata |
A copy of alldata that you clean and build on: -99 and -50 become NA here; Mutate Variables adds the _01 and _#CAT variables; Creating Composites adds the composite scores. Every analysis starts from it. |
Here, then every Lab 2 chapter |
mydata |
The subset for one analysis: the matched pairs, the complete cases, the two groups being compared. Made fresh in each test chapter from cleandata. |
Labs 4 and 5 |
No other data names, so that anyone reading your report (including you in three weeks) knows which stage a line of code is at. The file name is a placeholder: swap it for your team’s .cleandata file name (for example, Team 1 exporting on the October 9 lecture would use 10.09.2026.team1.cleandata.xlsx).
library(readxl)
# 1. alldata: the file exactly as exported. Never change it.
alldata <- read_excel("data/SWAPFILE.xlsx") # SWAP: your team's .cleandata file, e.g. 10.09.2026.team1.cleandata.xlsx
names(alldata) # the VARIABLES
head(alldata, 10) # the first 10 people
summary(alldata) # minimum and maximum of every variable
# 2. cleandata: the copy you clean and build on. Every later chapter adds to it.
cleandata <- alldata
cleandata[cleandata == -99] <- NA # prefer not to say -> missing
cleandata[cleandata == -50] <- NA # don't know -> missing| Criteria | Ask yourself |
|---|---|
| One header row | Is row 1 the variable names, and is row 2 a person (not question text)? |
| Rows | Does the number of rows match the number of responses in Qualtrics? |
| Variable names | Open your exported survey (.docx) next to names(alldata). Does every column name match the variable name you chose in Qualtrics, spelled the same way and in capital letters? |
| Unnamed questions | Do you see names such as Q17 or Q23_1? Those questions were never named. Fix the names in Qualtrics and export again. Do not rename them by hand in Excel. |
| Minimum and maximum | For each scale, do the minimum and maximum match the response options (for example, 1 to 5)? Are -99 and -50 gone? |
| Team agreement | Did every teammate import the same file, with the same date in its name? |