Load CSV files in RStudio

How to open a CSV file in RStudio with read.csv, readr or the Import Dataset menu, what parsing changes in your data, and how to avoid lost zeros, broken encodings and mangled headers.

Opening a CSV file in RStudio looks like a one-line job, but it is a transformation. Plain delimited text becomes a typed table in memory, and R decides how to split the text, what each column contains and what counts as missing. Most of the time that works well. Sometimes it quietly changes values that matter, such as ZIP codes, IDs with leading zeros, dates or accented names. This guide covers the main ways to load a CSV, what each one changes, and when to keep values as plain text.

Short recommendation

For most work, load CSV files with readr's read_csv(), either typed directly or generated through RStudio's Import Dataset dialog. It reads UTF-8 by default, handles a byte order mark, keeps column names as written and prints the column types it guessed, so you can check them. Base R's read.csv() needs no extra packages and is fine for small, clean files. With either function, the main tradeoff is automatic type guessing. It saves effort, but it can turn identifiers into numbers. Read a column as plain text (character) when its exact characters matter more than doing arithmetic on it. Common examples are postal codes, phone numbers, account or product IDs, and codes with leading zeros.

Three ways to open a CSV in RStudio

1. The Import Dataset dialog

In the Environment pane, choose Import Dataset, then From Text (readr) or From Text (base). You can also use the File menu's Import Dataset entry. The dialog previews the data and lets you set the delimiter, header row, encoding and per-column types. It also shows the R code it will run. Copy that code into your script so the import can be repeated. If you rely only on the menu, there is no record of the settings you chose.

2. Base R: read.csv()

df <- read.csv("data/sales.csv")

# Explicit version of the common defaults
df <- read.csv("data/sales.csv", header = TRUE, sep = ",",
               stringsAsFactors = FALSE, fileEncoding = "UTF-8")

str(df)    # check column types
head(df)   # look at the first rows

In R 4.0.0 and later, text columns are read as character by default, not as factors. In older versions, set stringsAsFactors = FALSE if you want plain text. For tab-separated files, use read.delim(). For files that use semicolons as separators and commas as decimal marks, which is common in many European locales, use read.csv2().

3. readr: read_csv()

library(readr)

df <- read_csv("data/sales.csv")
spec(df)   # show the column types readr chose

# Tab-separated and other delimiters
df_tsv <- read_tsv("data/sales.tsv")
df_semi <- read_delim("data/sales.csv", delim = ";",
                      locale = locale(decimal_mark = ","))

read_csv() returns a tibble, which is a data frame with stricter printing and subsetting behavior. If a value does not fit the guessed type, readr records a parsing problem instead of failing silently. Call problems(df) to see the affected rows. For very large files, data.table's fread() is another common option. It detects the separator automatically.

Finding and uploading the file

Many "file not found" errors come from the path, not the CSV. A relative path such as "data/sales.csv" is resolved from the working directory, which getwd() shows. An RStudio Project sets the working directory to the project folder, so relative paths keep working when someone else opens the project. file.choose() opens a file picker on desktop installs, but scripts that use it cannot run unattended. On RStudio Server or a cloud-hosted RStudio, the file must be on the server first. Use the Upload button in the Files pane, then read it by its path on the server.

getwd()                                  # where relative paths start
list.files("data")                       # confirm the file name and spelling
df <- read_csv(file.choose())            # interactive pick, desktop only

What loading a CSV actually changes

Reading a file does not modify the CSV on disk. The changes happen in the copy R builds in memory, and they only reach a file if you write one. These are the main changes:

  • Splitting: each line is cut into fields at the delimiter. Quoted fields can contain commas and line breaks. A wrong delimiter setting puts everything into one column or misaligns columns.
  • Type inference: columns that look numeric, logical or date-like are converted. "00501" becomes 501, and "1e5" becomes 100000.
  • Missing values: empty fields and the text "NA" become NA by default. If "NA" is a real value, such as a code for North America, set the na argument (readr) or na.strings (base R).
  • Column names: read.csv() runs check.names by default, so "Order Date" becomes "Order.Date" and names that start with digits get an "X" prefix. read_csv() keeps the original names, and you may need backticks to refer to them.
  • Encoding: bytes are interpreted as characters using the declared or default encoding. A mismatch shows up as garbled accented letters or symbols.
  • Whitespace: readr trims leading and trailing spaces from fields by default. Base R keeps them unless strip.white = TRUE.

Keeping exact values as plain text

If a column is an identifier rather than a quantity, tell R not to guess. You can override single columns or read every column as character and convert the ones you need afterward.

# readr: protect specific columns
df <- read_csv("data/customers.csv",
               col_types = cols(zip = col_character(),
                                customer_id = col_character()))

# readr: read everything as text
df <- read_csv("data/customers.csv",
               col_types = cols(.default = col_character()))

# base R equivalent
df <- read.csv("data/customers.csv", colClasses = "character")

Reading everything as character keeps every value exactly as written, but nothing is ready for calculation or sorting by number or date. That makes it useful for auditing a file or passing it through unchanged. It is a poor default for analysis.

Encoding and the byte order mark

Files saved from spreadsheet software sometimes start with a UTF-8 byte order mark. readr handles it. Base read.csv() may instead attach it to the first column name, which then appears as something like "X.U.FEFF.id" or "ï..id". In that case, set fileEncoding = "UTF-8-BOM". If accented characters look wrong, the file is probably not UTF-8. Try locale(encoding = "latin1") in readr or fileEncoding = "latin1" in base R, and compare a few known values against the source.

Will the data stay usable after you share it?

The import itself is safe to repeat because the source file is untouched. Problems usually appear when results are written back out and opened elsewhere.

  • write.csv() adds a column of row numbers unless you set row.names = FALSE. readr's write_csv() does not add one.
  • write_csv() writes UTF-8 without a byte order mark. Some spreadsheet programs may then misread non-ASCII characters. write_excel_csv() adds the mark for that case.
  • Opening an exported CSV in a spreadsheet and saving it again can re-apply type guessing there. Leading zeros and long numeric IDs are especially at risk. Keep an untouched copy of the original file.
  • Column names renamed by read.csv() stay renamed in anything you write, so downstream tools expecting "Order Date" will not find it.

If people or other systems need the exact original text, share the source CSV or a version written from all-character columns, not a file re-exported after type conversion.

Choosing a method

Situation | Suggested approach
Small, clean file; no extra packages | read.csv()
General analysis work | read_csv(), then check spec()
Unsure of settings; want a preview | Import Dataset dialog, then copy the generated code
Semicolon delimiter, comma decimals | read.csv2() or read_delim() with a locale
Tab-separated file | read.delim() or read_tsv()
IDs, ZIP codes, leading zeros | Set those columns to character
Very large file | data.table::fread() or read_csv()

Limits of this guide

The behavior described here reflects the documented defaults of base R, readr and RStudio's import dialog. No timed tests, file-size benchmarks or comparisons across specific spreadsheet applications were carried out. Defaults can change between package versions. Before you depend on a setting, check the help page in your installed version with ?read.csv or ?read_csv, and inspect the result with str() or spec().