Import CSV into R and RStudio

How to choose and import a CSV file into R or RStudio: what read.csv, readr and fread change in your data, how to keep it usable, and which method fits.

Is importing a CSV into R the right step for your data?

For most analysis work, importing a CSV into an R data frame is the practical choice. The data becomes something you can filter, summarize, model and plot. The decisive tradeoff is control versus convenience. Every import function guesses column types, missing values and column names unless you specify them, and a wrong guess can silently change values such as postal codes, account numbers or dates. A reasonable default is readr's read_csv(), or RStudio's import dialog using the readr option, with column types stated for any column that must stay exact. Base R's read.csv() suits situations where installing packages is not possible. data.table's fread() is a common choice for very large files. Keep working from the plain CSV, or import every column as character, when you only need to inspect, relay or archive the text exactly as written.

What importing a CSV actually changes

Importing does not modify the file on disk. R reads the text, splits it into fields using the delimiter and quoting rules, and builds a data frame (or a tibble or data.table) in memory. This is a structural conversion from text into typed columns, not a visual effect. Terms like "reverse", "mirror" or "font", which describe text styling tools, do not apply. The changes that matter happen in how each field is interpreted:

  • Types: text that looks numeric becomes a number, which drops leading zeros ("00742" becomes 742) and can lose precision in very long digit strings.
  • Missing values: depending on the function and its settings, empty fields and the string "NA" may become NA rather than text.
  • Column names: read.csv() defaults to check.names = TRUE, which turns a header like "Unit Price" into Unit.Price. readr keeps the original names and only repairs empty or duplicate ones.
  • Strings: since R 4.0.0, read.csv() keeps text as character by default instead of converting it to factors.
  • Encoding: accented and non-Latin characters display correctly only if the declared encoding matches how the file was saved.
  • Dates: readr may parse ISO-style dates automatically. read.csv() leaves them as character until you convert them.

There is also a difference between stored values and what you see on screen. The console prints numbers to about seven significant digits by default, and the RStudio data viewer formats values for display, but the underlying values keep full precision. A number that looks rounded in the console has not been changed.

Choosing the file: file.choose() versus a path

"Choose a CSV file" can mean two things in R: picking the file interactively, or deciding which function to read it with. For interactive picking, file.choose() returns the selected path. Depending on the platform and interface, it opens a file dialog or asks for a filename in the console.

# Pick the file interactively, then read it
path <- file.choose()
df <- read.csv(path)

# Reproducible alternative: a path relative to the working directory
getwd()
df <- read.csv("data/sales.csv")

file.choose() is convenient for one-off exploration, but a script that relies on it cannot be rerun without a person clicking through a dialog. For shared or repeated work, write the path into the script. An RStudio Project sets the working directory to the project folder, so relative paths such as "data/sales.csv" work for anyone who opens the project.

Comparing the main import methods

Method | Package | Returns | Delimiter handling | Type handling | Best fit
read.csv() | utils (base R) | data.frame | Comma by default; read.csv2() for semicolons; read.delim() for tabs | Guesses per column; override with colClasses | No package installs, small to medium files
read_csv() | readr | tibble | Comma; read_csv2() and read_tsv() for other formats | Guesses from a sample of rows; override with col_types; reports parsing problems | General analysis and tidyverse workflows
fread() | data.table | data.table | Detects the separator automatically | Guesses per column; override with colClasses | Large files and data.table workflows
Import Dataset dialog | RStudio, using base R or readr | Same as the chosen backend | Set in a preview window | Set per column in the preview | Learning, or files with unusual layouts

The rows above describe documented behavior. No timing or memory tests were run for this article, so no claim is made about how much faster one function is than another on your files. Speed only becomes the deciding factor for large files. For typical sizes, the more important difference is how clearly each function reports and lets you correct type guesses. readr's problems() and spec() functions make this explicit, which is the main reason it is the default recommendation here.

Base R: read.csv()

df <- read.csv("data/sales.csv",
               fileEncoding = "UTF-8",
               na.strings = c("", "NA"),
               colClasses = c(zip = "character"),
               check.names = FALSE)
str(df)

Setting colClasses for identifier columns prevents lost leading zeros. check.names = FALSE keeps the headers as written. If the first column name shows stray characters, the file probably has a byte order mark, and fileEncoding = "UTF-8-BOM" usually fixes it.

readr: read_csv()

library(readr)

df <- read_csv("data/sales.csv",
               col_types = cols(zip = col_character()),
               locale = locale(encoding = "UTF-8"))

spec(df)      # the column types readr used
problems(df)  # rows that failed to parse

readr guesses types from a sample of rows. A column whose first values are numeric but which contains text further down may therefore be parsed as numeric, with the later text values turned into NA. Those rows show up in problems(). Increasing guess_max, or stating col_types, resolves this.

data.table: fread()

library(data.table)

dt <- fread("data/sales.csv", colClasses = c(zip = "character"))

fread() returns a data.table, which also works as a data frame but has its own syntax for subsetting and updating. Choose it when you plan to work in data.table, or when file size makes import time noticeable.

Importing through the RStudio menu

In RStudio, File > Import Dataset > From Text offers a base R option and a readr option. The dialog lets you browse for the file, preview the parsed result, change the delimiter and column types, and see the R code it will run. Copying that code into your script gives you the convenience of the preview and the reproducibility of a written import. The import itself is the same as calling the underlying function directly, so the caveats in this article apply to it as well.

TSV and semicolon-separated files

read.delim("data/file.tsv")         # base R, tab-separated
readr::read_tsv("data/file.tsv")    # readr, tab-separated

read.csv2("data/file.csv")          # semicolon separator, comma decimal
readr::read_csv2("data/file.csv")

Files exported with some European regional settings use semicolons between fields and commas as decimal marks. Reading such a file with read.csv() typically produces a single column, or numbers stored as text. If the result has one wide column, check the delimiter first.

Will the data stay readable and usable after sharing?

A CSV is plain text, so it copies, versions and opens almost anywhere. Most problems come from round trips through other software rather than from R itself.

  • Writing back out: write.csv() adds a row-name column unless you set row.names = FALSE. readr's write_csv() does not add one and writes UTF-8.
  • Spreadsheet round trips: opening a CSV in a spreadsheet and saving it again can reformat dates, strip leading zeros or change the delimiter. If the file passed through a spreadsheet, check those columns after re-importing.
  • Encoding: share files as UTF-8 and state the encoding in the import call. This keeps non-English text intact for the next person.
  • Reproducibility: a written import call with explicit types documents your assumptions. A sequence of menu clicks does not.
  • Accessibility: CSV and R scripts are plain text, which assistive technologies can generally read. RStudio has a screen reader support setting in its accessibility options. This article did not test it with any specific screen reader, so verify the setup you depend on. Grid-style data viewers can be harder to navigate than printed console output, and functions like head(), str() and summary() give a linear, text-only view of the same data.

Quick checks after any import

  • Compare nrow(df) and ncol(df) with what you expect from the file.
  • Run str(df) or dplyr::glimpse(df) to confirm each column's type.
  • Inspect identifier and date columns directly with head().
  • With readr, run problems(df) and resolve any reported rows.
  • Count NA values per column with colSums(is.na(df)) to catch fields that failed to parse.

Gaps in this overview

This guide relies on the documented behavior of base R, readr, data.table and RStudio. No performance measurements, version-specific test results or file samples were available, and none are claimed. Defaults can change between package versions, so check the help page for your installed version (for example, ?read.csv or ?readr::read_csv) before relying on a particular default.