Importing survey data into R for analysis means loading datasets from file formats like CSV, Excel, SPSS (.sav), Stata (.dta), SAS (.sas7bdat), Google Sheets, Qualtrics, JSON, or databases into R’s memory as data frames or tibbles so you can clean, transform, and analyze them using R’s statistical tools. The process uses specialized packages such as readr for CSV files, readxl for Excel, haven for SPSS/Stata/SAS, googlesheets4 for Google Sheets, qualtRics for Qualtrics, and rio as a universal importer.
If you are working through this for the first time, the quickest path is to install the tidyverse, haven, and rio packages, point R at your file with the correct function, and verify the result with glimpse(). This guide walks through every major survey data format with copy-paste code examples, troubleshooting for the errors beginners hit most, and a comparison table so you can find the right method fast.
I have spent years working with survey datasets from academic research projects, public health studies, and social science surveys. Every format below comes from real workflows I have used, including the painful troubleshooting steps. By the end of this guide, you will know exactly which function to call for any survey file format and how to handle the labeled data, missing values, and survey weights that come with it.
Survey data has unique characteristics that make importing it different from loading a generic spreadsheet. Survey files from SPSS, Stata, and SAS carry value labels (1 = “Male”, 2 = “Female”), variable labels (long descriptive names), skip patterns, and survey design metadata like weights and strata. R can handle all of this, but you need the right packages and a clear post-import workflow.
Table of Contents
Prerequisites and Setup
Before you import anything, you need R, RStudio, and the right packages installed. RStudio is not strictly required, but it makes importing and exploring data significantly easier, especially with its Import Dataset GUI for beginners.
Download R from the CRAN website and RStudio from the Posit downloads page. Install R first, then RStudio. On Mac, both install like standard applications. On Windows, accept the default installation options unless your organization specifies otherwise.
Once R and RStudio are running, install the core packages for survey data import. Open RStudio and run this in the console:
# Core import packages
install.packages("tidyverse") # includes readr, dplyr, tibble, forcats
install.packages("haven") # SPSS, Stata, SAS
install.packages("readxl") # Excel files
install.packages("rio") # universal importer
install.packages("data.table") # fast import for large files
# Platform-specific survey tools
install.packages("googlesheets4") # Google Sheets
install.packages("qualtRics") # Qualtrics
install.packages("jsonlite") # JSON / API responses
install.packages("httr2") # API requests
install.packages("DBI") # Database connections
install.packages("odbc") # Database drivers
# Post-import and analysis
install.packages("labelled") # Work with labeled data
install.packages("survey") # Survey analysis
install.packages("srvyr") # Tidyverse-style survey analysis
install.packages("here") # Reproducible file paths
After installation, load the packages at the top of your script. You only need to load the ones you will use for that session.
library(tidyverse) # readr, dplyr, tibble loaded automatically
library(haven) # for SPSS/Stata/SAS
library(readxl) # for Excel
library(here) # for reproducible paths
Set your working directory or, better, use the here package for reproducible file paths. The here package automatically finds your project root folder, so your code works on any machine without changing paths.
# Option A: Set working directory (less reproducible)
setwd("C:/Users/yourname/projects/survey_analysis")
# Option B: Use here package (recommended)
library(here)
here() # shows your project root
# Files referenced as: here("data", "survey_raw.csv")
Mac vs Windows note: On Windows, use forward slashes in file paths ("C:/Users/data/survey.csv") or double backslashes ("C:\Users\data\survey.csv"). Single backslashes cause errors because R interprets them as escape characters. Mac paths use forward slashes naturally ("~/Documents/survey.csv").
Quick Reference: Which Import Method Should I Use?
Use this table to find the right function for your file format. Each method is explained in detail in its own section below.
| File Format | Extension | Package | Function |
|--------------------|--------------|-------------|---------------------------|
| CSV | .csv | readr | read_csv() |
| TSV / delimited | .tsv .txt | readr | read_tsv() / read_delim() |
| Excel | .xlsx .xls | readxl | read_excel() |
| SPSS | .sav .por | haven | read_sav() |
| Stata | .dta | haven | read_dta() |
| SAS | .sas7bdat | haven | read_sas() |
| Google Sheets | (URL/ID) | googlesheets4 | read_sheet() |
| Qualtrics | (API) | qualtRics | fetch_survey() |
| JSON / API | .json | jsonlite | fromJSON() |
| Database | (connection) | DBI + odbc | dbGetQuery() |
| Any format | (auto-detect)| rio | import() |
| Large CSV (fast) | .csv | data.table | fread() |
If you are unsure of your file format, rio::import() auto-detects the extension and applies the correct function. It is the fastest way to get started, though format-specific functions give you more control over import parameters.
Method 1: Import CSV and Delimiter-Separated Files
CSV is the most common format for survey data exports. Google Forms, SurveyMonkey, LimeSurvey, and most online survey platforms can export to CSV. R offers three main approaches: read.csv() from base R, read_csv() from the readr package, and fread() from data.table for large files.
Using read_csv() from readr
The read_csv() function from the readr package (part of tidyverse) is the recommended choice for most survey CSV files. It is faster than base R, handles column types better, and returns a tibble instead of a data frame.
library(readr)
# Basic import
survey_data <- read_csv("data/survey_responses.csv")
# With explicit settings for survey data
survey_data <- read_csv(
"data/survey_responses.csv",
na = c("", "NA", "N/A", "999", "-999"), # Treat these as missing
col_names = TRUE, # First row is column names
skip = 0, # Skip rows if metadata header exists
locale = locale(encoding = "UTF-8") # Handle special characters
)
# Specify column types manually for control
survey_data <- read_csv(
"data/survey_responses.csv",
col_types = cols(
respondent_id = col_character(),
age = col_integer(),
gender = col_factor(),
satisfaction = col_integer(),
open_response = col_character()
)
)
One common issue with survey CSVs is that column names starting with numbers get an “X” prefix automatically. This happens because R variable names cannot start with a digit. Use .name_repair to control this behavior.
# Keep original names (with backticks for access)
survey_data <- read_csv("data/survey.csv", .name_repair = "minimal")
# Use unique names (X1, X2, etc. for duplicates)
survey_data <- read_csv("data/survey.csv", .name_repair = "universal")
Base R: read.csv()
Base R’s read.csv() works without any packages installed. It is slower and returns a data frame with strings as factors by default in older R versions. Use it when you cannot install packages or need legacy compatibility.
# Base R CSV import
survey_data <- read.csv(
"data/survey_responses.csv",
header = TRUE,
sep = ",",
stringsAsFactors = FALSE,
na.strings = c("NA", "", "999")
)
Other delimited formats: TSV, semicolon-separated
European survey data often uses semicolons instead of commas as the delimiter. Tab-separated files (TSV) are common for large exports. Use read_tsv() for tabs and read_delim() for any other delimiter.
# Tab-separated
survey_tsv <- read_tsv("data/survey.tsv")
# Semicolon-separated (common in European data)
survey_semi <- read_delim("data/survey.csv", delim = ";")
# Pipe-separated
survey_pipe <- read_delim("data/survey.txt", delim = "|")
Fast import for large survey datasets: fread()
If your survey file has millions of rows (like Census data or large panel surveys), use data.table::fread(). It is dramatically faster than read_csv() for big files.
library(data.table)
# Fast import for large files
big_survey <- fread("data/large_survey.csv",
na.strings = c("NA", "", "999"),
stringsAsFactors = FALSE)
# Convert to tibble if you prefer tidyverse workflow
big_survey <- as_tibble(big_survey)
Reddit users in r/rstats consistently recommend fread() for any CSV file over 500 MB. The speed difference can be 10x or more compared to read_csv().
Method 2: Import Excel Files (.xlsx and .xls)
Many researchers store survey data in Excel spreadsheets. The readxl package handles both .xlsx and .xls files without requiring Excel or Java to be installed on your system.
Basic Excel import with readxl
library(readxl)
# Import first sheet
survey_excel <- read_excel("data/survey_data.xlsx")
# Specify sheet by name
survey_excel <- read_excel("data/survey_data.xlsx", sheet = "Responses")
# Specify sheet by index
survey_excel <- read_excel("data/survey_data.xlsx", sheet = 2)
# Skip metadata rows at the top
survey_excel <- read_excel(
"data/survey_data.xlsx",
skip = 2, # Skip first 2 rows (often title/subtitle)
col_names = TRUE # Row 3 becomes column names
)
# Specify a cell range
survey_excel <- read_excel("data/survey_data.xlsx", range = "A1:Z500")
# Set column types explicitly
survey_excel <- read_excel(
"data/survey_data.xlsx",
col_types = c("text", "numeric", "numeric", "text", "date")
)
# Handle empty cells as NA
survey_excel <- read_excel("data/survey_data.xlsx", na = c("", "NA", "N/A"))
readxl vs openxlsx vs xlsx
Three packages handle Excel files in R, and they serve different purposes. readxl is best for reading data only and is part of the tidyverse ecosystem. openxlsx can both read and write Excel files with formatting. xlsx requires Java, which causes installation problems on many systems.
# openxlsx (read and write with formatting)
library(openxlsx)
survey_data <- read.xlsx("data/survey.xlsx", sheet = 1)
# For most survey import tasks, readxl is the best choice.
# Use openxlsx when you need to write formatted Excel output.
Tip: Excel files from Qualtrics exports often have multiple header rows (variable names in row 1, question text in row 2). Use skip = 1 to start from row 2, or import twice and combine the metadata.
Method 3: Import SPSS, Stata, and SAS Files
Survey data from academic and government research is frequently stored in proprietary statistical software formats. The haven package reads SPSS (.sav), Stata (.dta), and SAS (.sas7bdat) files and preserves the metadata that makes survey data special: value labels, variable labels, and tagged missing values.
Importing SPSS files (.sav)
library(haven)
# Basic SPSS import
survey_spss <- read_sav("data/survey.sav")
# The result is a tibble with haven_labelled columns
# Value labels and variable labels are preserved
# Convert all labeled columns to factors during import
survey_spss <- read_sav("data/survey.sav") |>
mutate(across(where(is.labelled), as_factor))
# Or convert to factors with numeric codes retained
survey_spss <- read_sav("data/survey.sav") |>
mutate(across(where(is.labelled), ~as_factor(.x, levels = "both")))
Importing Stata files (.dta)
# Basic Stata import
survey_stata <- read_dta("data/survey.dta")
# Stata version-specific options
survey_stata <- read_dta("data/survey.dta", encoding = "latin1")
# Convert labeled data to factors
survey_stata <- read_dta("data/survey.dta") |>
mutate(across(where(is.labelled), as_factor))
Importing SAS files (.sas7bdat)
# Basic SAS import
survey_sas <- read_sas("data/survey.sas7bdat")
# SAS transport files (.xpt)
survey_xpt <- read_xpt("data/survey.xpt")
Understanding Labeled Data from SPSS, Stata, and SAS
This is the single most confusing aspect of importing survey data into R for newcomers. SPSS, Stata, and SAS store two types of metadata that R does not have natively: value labels and variable labels.
Value labels map numeric codes to text descriptions. For example, a gender variable stores 1 and 2 but displays “Male” and “Female.” A satisfaction variable stores 1 through 5 but displays “Very Dissatisfied” through “Very Satisfied.”
Variable labels are long descriptive names for each column. A variable might be named “Q1” internally but have the label “How satisfied are you with your current housing situation?”
When you import with haven, these become haven_labelled class vectors. They look odd when you first inspect them because R does not have a native equivalent. You have three options for handling them:
library(haven)
library(labelled)
# Option 1: Convert to factors (most common for analysis)
survey_data <- read_sav("data/survey.sav") |>
mutate(across(where(is.labelled), as_factor))
# Option 2: Strip labels and keep raw numeric values
survey_data <- read_sav("data/survey.sav") |>
mutate(across(where(is.labelled), zap_labels))
# Option 3: Keep as haven_labelled and convert selectively
survey_data <- read_sav("data/survey.sav")
# Convert specific columns when needed for analysis
survey_data$gender <- as_factor(survey_data$gender)
Tagged missing values
SPSS and Stata support tagged missing values, where different types of missingness get distinct codes. For example, -1 means “Not applicable” and -7 means “Refused to answer.” Haven preserves these as tagged NA values, which you can inspect and convert.
# Inspect tagged missing values
library(labelled)
# See what tagged NAs exist
na_values(survey_data$income)
# Convert all tagged NAs to regular NA
survey_data <- survey_data |>
mutate(across(everything(), ~if_else(is.na(.), NA, .)))
# Or use zap_missing to remove tagged NA attributes
survey_data <- read_sav("data/survey.sav") |>
zap_missing()
Creating a data dictionary from labeled data
One advantage of haven-imported data is that you can generate a data dictionary documenting every variable and its labels. This is essential for survey research documentation.
library(labelled)
# Generate a data dictionary
dictionary <- generate_dictionary(survey_data)
print(dictionary)
# This produces a tibble with:
# - variable name
# - variable label
# - value labels
# - data type
# - number of missing values
Method 4: Import via RStudio GUI
RStudio provides a graphical Import Dataset button that lets you import data without writing code. This is the easiest entry point for beginners, though experienced users eventually switch to code for reproducibility.
Step-by-step: RStudio Import Dataset
Open RStudio and look at the Environment pane in the top-right corner. Click the “Import Dataset” dropdown. You will see options for From Text (readr), From Excel (readxl), From SPSS/SAS/Stata (haven), and From Other Statistical Software.
Select the matching option for your file format. A file browser opens. Navigate to your survey data file and select it. RStudio then shows a preview window where you can adjust settings like delimiter, skip rows, column types, and NA values before committing.
As you change settings, RStudio generates the corresponding code in the bottom of the preview window. Copy that code into your script before clicking Import. This way, you get the convenience of the GUI plus a reproducible code record.
GUI vs code: which should you use?
The GUI is great for exploring an unfamiliar file or for one-time imports. However, code-based import is strongly preferred for any analysis you will repeat or share. Forum users on r/RStudio frequently mention that GUI-generated code sometimes breaks when rerun because it hardcodes absolute file paths that differ between machines.
Use the GUI to explore your data and discover the right import settings. Then write clean, portable code using the here package for file paths. This gives you the best of both approaches.
Method 5: Import from Google Sheets
If you collect survey data through Google Forms, responses land in a Google Sheet. The googlesheets4 package reads directly from Google Sheets without manual CSV export.
Reading a Google Sheet into R
library(googlesheets4)
# Read a public sheet by URL
survey_gs <- read_sheet("https://docs.google.com/spreadsheets/d/SHEET_ID/edit")
# Read by sheet ID
survey_gs <- read_sheet("1AbCdEfGhIjKlMnOpQrStUv")
# Read a specific sheet (tab)
survey_gs <- read_sheet("SHEET_ID", sheet = "Form Responses 1")
# Specify column types
survey_gs <- read_sheet("SHEET_ID", col_types = "cniic")
Authentication for private sheets
Public sheets can be read without authentication. Private sheets require you to authorize the googlesheets4 package to access your Google account. The first time you call read_sheet() on a private sheet, a browser window opens for OAuth authentication.
# This triggers browser auth on first run
survey_gs <- read_sheet("SHEET_ID")
# For scripts running on servers, use a service account
# Set up a .json service account key and configure auth
gs4_auth(email = "[email protected]",
path = "service-account-key.json")
Once authenticated, your session stays authorized for future reads in that R session. Google Forms data flows into the first sheet tab automatically, so sheet = "Form Responses 1" usually captures the live survey responses.
Method 6: Import from Qualtrics
Qualtrics is one of the most widely used survey platforms in academic and market research. The qualtRics package pulls survey responses directly through the Qualtrics API, eliminating manual CSV downloads.
Setting up Qualtrics API access
Log into your Qualtrics account. Go to Account Settings, then Qualtrics IDs. Find your API token and save it securely. You will also need your data center ID (found in your account URL, like “youruniversity.qualtrics.com”).
library(qualtRics)
# Store your API credentials
qualtrics_api_credentials(
api_key = "YOUR_API_TOKEN",
base_url = "youruniversity.qualtrics.com"
)
# List available surveys
surveys <- all_surveys()
print(surveys)
# Fetch survey responses
survey_data <- fetch_survey(
surveyID = "SV_XXXXXXXXXXXX",
save_dir = tempdir(), # Cache download
force_request = TRUE, # Bypass cache
labelision = TRUE, # Use question labels (not import names)
convert_labels = FALSE # Keep as haven_labelled
)
The labelision argument controls whether you get human-readable question text or the raw Qualtrics internal names. Set convert_labels = FALSE to keep value labels as haven_labelled objects, which you can then convert to factors as shown in Method 3.
Method 7: Import from APIs and JSON
Modern survey platforms often expose data through REST APIs that return JSON. This includes Typeform, SurveyMonkey, and custom-built survey tools. R handles JSON through the jsonlite package, and API requests through httr2 or httr.
Reading JSON files
library(jsonlite)
# Read a local JSON file
survey_json <- fromJSON("data/survey_export.json")
# Read from a URL
survey_json <- fromJSON("https://api.surveyplatform.com/responses")
# JSON from APIs is often nested. Flatten it:
survey_flat <- fromJSON("data/survey.json") |>
as_tibble()
# Deeply nested responses need flatten recursive
survey_flat <- fromJSON("data/survey.json", flatten = TRUE) |>
as_tibble()
API requests with httr2
library(httr2)
library(jsonlite)
# Build an API request
request <- request("https://api.surveytool.com/v1/responses") |>
req_headers(Authorization = "Bearer YOUR_API_KEY") |>
req_url_query(survey_id = "12345", limit = 1000)
# Perform the request
response <- request |>
req_perform() |>
resp_body_json()
# Convert to tibble
survey_api <- response$data |>
as_tibble()
JSON survey data often contains nested lists where each response has sub-objects for answers, metadata, and timing. Use tidyr::unnest() to flatten these into a usable tabular format.
library(tidyr)
# Flatten nested answer objects
survey_flat <- survey_api |>
unnest(answers, names_repair = "universal")
Method 8: Import from Databases
Large-scale survey programs often store data in SQL databases. R connects to databases through the DBI package with database-specific drivers via odbc.
Connecting to a database
library(DBI)
library(odbc)
# List available drivers
odbcListDrivers()
# Connect to PostgreSQL
con <- dbConnect(
odbc::odbc(),
dsn = "survey_database",
uid = "your_username",
pwd = "your_password"
)
# Or connect by driver name
con <- dbConnect(
odbc::odbc(),
driver = "PostgreSQL",
server = "db.server.com",
database = "surveys",
uid = "user",
pwd = "password",
port = 5432
)
Querying survey data
# Read entire table
survey_db <- dbReadTable(con, "survey_responses")
# Run a SQL query
survey_db <- dbGetQuery(con, "
SELECT respondent_id, age, gender, satisfaction
FROM survey_responses
WHERE wave = '2025'
")
# Disconnect when done
dbDisconnect(con)
For very large survey tables, use dbplyr to write dplyr code that translates to SQL. This lets you filter and aggregate on the database server before pulling data into R’s memory.
library(dbplyr)
# Reference a table lazily
survey_lazy <- tbl(con, "survey_responses")
# Filter on the database side
filtered <- survey_lazy |>
filter(satisfaction >= 3) |>
select(respondent_id, age, satisfaction) |>
collect() # Pull into R memory
The All-in-One Approach: rio::import()
The rio package provides a single import() function that auto-detects file format from the extension and applies the appropriate reader. It is the simplest way to import data when you do not want to remember which package handles which format.
library(rio)
# Auto-detect format from extension
survey_csv <- import("data/survey.csv")
survey_xls <- import("data/survey.xlsx")
survey_sav <- import("data/survey.sav")
survey_dta <- import("data/survey.dta")
survey_sas <- import("data/survey.sas7bdat")
# Export works the same way
export(survey_csv, "data/survey_cleaned.rds")
When to use rio vs format-specific functions: Use rio::import() for quick exploration or when you trust the file format. Use format-specific functions like read_csv() or read_sav() when you need fine-grained control over column types, missing value handling, or labeled data conversion. Rio abstracts away these parameters, which is convenient but can hide issues.
Forum users on r/rstats praise rio for simplicity but note that it sometimes guesses column types incorrectly on messy survey data. For production survey analysis workflows, most experienced R users prefer explicit format-specific functions.
Post-Import Data Cleaning Checklist
After importing survey data, run through this checklist before starting analysis. These steps catch common import problems early.
Step 1: Verify the import with glimpse, summary, and head
# Check structure
glimpse(survey_data)
# Statistical summary of every column
summary(survey_data)
# First few rows
head(survey_data)
# Last few rows (catches trailing junk)
tail(survey_data)
# Dimensions
dim(survey_data)
nrow(survey_data)
ncol(survey_data)
Look for unexpected column types (a numeric variable imported as character), suspicious missing value counts, and rows that should not be there (like trailing notes or footer text from Excel).
Step 2: Clean column names
Survey exports often have messy column names with spaces, special characters, or Qualtrics-style prefixes like “Q1_What is your age”.
library(janitor)
# Clean to snake_case
survey_data <- survey_data |>
clean_names()
# Or manually rename
survey_data <- survey_data |>
rename(
respondent_id = V1,
age = Q1,
gender = Q2,
satisfaction = Q3
)
Step 3: Handle missing values
Survey data uses various codes for missingness. Recode them consistently before analysis.
# Recode common missing value codes
survey_data <- survey_data |>
mutate(
across(everything(), ~na_if(.x, -99)),
across(everything(), ~na_if(.x, -77)),
across(everything(), ~na_if(.x, "DK")),
across(everything(), ~na_if(.x, "REFUSED"))
)
# Check missingness pattern
library(naniar)
vis_miss(survey_data)
miss_summary(survey_data)
Step 4: Convert labeled data to factors
If you imported SPSS, Stata, or SAS files, convert haven_labelled columns to factors for analysis.
library(haven)
# Convert all labelled columns to factors
survey_data <- survey_data |>
mutate(across(where(is.labelled), as_factor))
# Verify conversion
glimpse(survey_data)
Step 5: Set up survey design objects (if using weights)
If your survey data includes sampling weights, strata, or cluster variables, create a survey design object after import. This is the bridge between data import and survey-weighted analysis.
library(survey)
# Create a survey design object
survey_design <- svydesign(
ids = ~cluster_id,
strata = ~stratum,
weights = ~weight,
data = survey_data
)
# Or use srvyr for tidyverse-style syntax
library(srvyr)
survey_design <- survey_data |>
as_survey_design(
ids = cluster_id,
strata = stratum,
weights = weight
)
How to Import Survey Data into R for Analysis: Troubleshooting Common Errors
These are the errors that come up most often when you learn how to import survey data into R for analysis. Each has a straightforward fix.
Error: “File does not exist” or “cannot open file”
This is the most common import error. It almost always means R cannot find your file at the specified path. Check your working directory with getwd() and confirm the file exists with file.exists("path/to/file.csv").
# Debug file path issues
getwd()
list.files("data/") # See what is actually in your data folder
file.exists("data/survey.csv")
On Windows, replace single backslashes with forward slashes. "C:Usersdatasurvey.csv" fails. "C:/Users/data/survey.csv" works. The here package eliminates this problem entirely by managing paths relative to your project root.
Error: “More columns than column names” or “embedded null”
This happens when your CSV has inconsistent delimiters, often caused by commas inside unquoted text fields (common in open-ended survey responses). Switch from read.csv() to read_csv(), which handles quoting more robustly. If the problem persists, inspect the file around the problem row.
# read_csv is more tolerant of messy quoting
survey_data <- read_csv("data/survey.csv", quote = """)
Error: Weird column names with X prefixes
R adds an “X” prefix to column names that start with a number because R variable names cannot begin with digits. Survey exports from Qualtrics and other platforms often produce names like “Q1”, “Q2_1”, and numbered matrix questions.
# Check your column names
names(survey_data)
# Option 1: Use clean_names to fix them
library(janitor)
survey_data <- survey_data |> clean_names()
# Option 2: Supply names manually
survey_data <- read_csv("data/survey.csv",
col_names = c("id", "age", "gender", "satisfaction"),
skip = 1)
Error: Encoding issues with special characters
Survey data from non-English sources often has accented characters or non-Latin scripts that display incorrectly after import. Specify the file encoding explicitly.
# Common encodings for international survey data
survey_data <- read_csv("data/survey.csv", locale = locale(encoding = "UTF-8"))
survey_data <- read_csv("data/survey.csv", locale = locale(encoding = "Latin1"))
survey_data <- read_csv("data/survey.csv", locale = locale(encoding = "Windows-1252"))
If you see “é” instead of “e-acute” or question marks replacing characters, encoding is the culprit. Trial UTF-8 first, then Latin1 for older European datasets.
Error: Out of memory on large survey files
Very large survey datasets (Census microdata, large panel surveys with millions of rows) can exceed R’s default memory limits. Use data.table::fread() for faster, more memory-efficient reading. For extreme cases, read data in chunks or use the arrow package for out-of-memory analysis.
# Fast reading with data.table
library(data.table)
big_survey <- fread("data/huge_survey.csv")
# Chunked reading with readr
library(readr)
chunks <- read_csv_chunked("data/huge_survey.csv",
DataFrameCallback$new(function(x, pos) x),
chunk_size = 10000)
# Arrow for out-of-memory analysis
library(arrow)
big_survey <- open_dataset("data/huge_survey.csv")
Error: Column type mismatches
Sometimes a numeric column imports as character because of stray text values (like “N/A” or “REFUSED” mixed with numbers). Inspect the column and either fix the values or specify types explicitly during import.
# Inspect problem column
unique(survey_data$age)
# Fix during import with col_types
survey_data <- read_csv("data/survey.csv",
col_types = cols(age = col_character())) # Read as char first
# Then clean and convert
survey_data <- survey_data |>
mutate(age = as.numeric(age))
FAQ’s
How do I import survey data into R for analysis on Mac?
What is the best way to import survey data into R?
How do I import data into R?
How do I import data into RStudio?
How do I import an Excel file in RStudio?
How do I handle labeled data from SPSS or Stata in R?
What is the difference between read.csv() and read_csv()?
Can I manually input survey data in R?
Conclusion
Knowing how to import survey data into R for analysis means matching your file format to the right package: readr for CSV, readxl for Excel, haven for SPSS/Stata/SAS, googlesheets4 for Google Sheets, qualtRics for Qualtrics, jsonlite for API responses, and DBI for databases. The rio package serves as a universal fallback when you want format auto-detection.
The critical steps after import are always the same: verify with glimpse(), clean column names, handle missing values, convert labeled data to factors, and set up a survey design object if you are working with weighted data. These post-import steps determine whether your analysis runs smoothly or breaks down on edge cases.
Start with the quick reference table to find your format, copy the matching code example, and run through the troubleshooting section if you hit errors. Survey data import becomes routine after the first few times through this workflow.