Get the mtcars dataset as CSV

How to export R's built-in mtcars dataset to CSV or TSV without losing the car model names, plus how to check the file and when plain CSV is the right format.

The mtcars dataset ships with base R, so you don't need to download it. You can produce a CSV copy yourself from any R installation, which avoids relying on an unverified file from someone else. Exporting it is a single command. The main thing to get right is the car model names: R stores them as row names, not as a regular column, and the default export handles them in a way that often trips people up when the file is read back.

Is CSV the right format for your use?

For most uses, yes. CSV is plain text, so spreadsheets, Python, databases and command-line tools can all read it, and the file is small enough to inspect by eye. The tradeoff is that CSV keeps only values. It does not store data types, factor levels, column descriptions or the dataset's help documentation. When the file is read back, every tool has to infer the types again.

If you are staying inside R, you usually don't need a file at all, because typing mtcars loads the data. If you need an exact R object, including attributes, saveRDS() preserves more than CSV does. CSV is the better choice when the data has to leave R, be shared with people using other tools, or be version-controlled as readable text.

What the conversion actually changes

Exporting mtcars is not a visual or stylistic text transformation. The characters are not reversed, mirrored or swapped for styled Unicode. The conversion serializes an in-memory data frame into delimited text: one header line, then one line per car, with values separated by commas (or tabs, for TSV). The numbers are written as ordinary decimal text.

It helps to separate what the file stores from how a program displays it. The CSV stores the characters that R wrote. A spreadsheet may then show those values rounded, right-aligned or reformatted. That display is a presentation layer and does not change the file unless you save over it from the spreadsheet.

According to R's documentation, mtcars has 32 rows and 11 numeric columns. You can confirm this with dim(mtcars). Each row is a car model. The model name is the row name, not one of the 11 columns. The columns are:

  • mpg – miles per (US) gallon
  • cyl – number of cylinders
  • disp – displacement (cubic inches)
  • hp – gross horsepower
  • drat – rear axle ratio
  • wt – weight (1000 lbs)
  • qsec – quarter-mile time
  • vs – engine shape (0 = V-shaped, 1 = straight)
  • am – transmission (0 = automatic, 1 = manual)
  • gear – number of forward gears
  • carb – number of carburetors

Two details are easy to lose in a CSV. First, vs and am are stored as 0/1 numbers, so the file carries no labels for them. Anyone using the CSV needs the coding listed above. Second, the row names need explicit handling, as described in the next section.

Exporting from R

The shortest version is write.csv(mtcars, "mtcars.csv"). By default, write.csv writes the row names as the first column and leaves that column's header empty. When the file is read back with read.csv, the column typically comes back with a placeholder name such as X, and other tools may label it differently or not at all. A cleaner approach is to turn the row names into a named column before writing:

mtcars_out <- cbind(model = rownames(mtcars), mtcars)
write.csv(mtcars_out, "mtcars.csv", row.names = FALSE)

For a tab-separated file, use write.table with a tab delimiter. Quoting can be turned off here because neither the model names nor the numbers contain tabs:

write.table(mtcars_out, "mtcars.tsv", sep = "\t",
            row.names = FALSE, quote = FALSE)

Avoid write.csv2 unless your recipients expect it. It uses semicolons as separators and commas as decimal marks, a convention common in some European locales but not the usual expectation in the US.

Getting it in Python without R

If R isn't installed, statsmodels can fetch R datasets from a community-maintained mirror. This requires a network connection, and you are trusting a third-party copy rather than your own R installation.

import statsmodels.api as sm

mtcars = sm.datasets.get_rdataset("mtcars").data
mtcars.to_csv("mtcars.csv", index_label="model")

Before saving, look at mtcars.head(). Check whether the model names arrived as the DataFrame index or as an ordinary column, and adjust the export accordingly. If they are already a column, pass index=False instead so you don't add an extra numbered index column.

Will the file stay readable and usable after sharing?

Copy and paste: because CSV is plain text, copying it between editors, terminals or chat tools keeps the characters intact. The model names are plain ASCII, so encoding problems are unlikely. Pasting raw CSV into a spreadsheet cell, however, may put each whole line into a single column until you run the program's text-to-columns or import feature.

Spreadsheets: mtcars contains only plain numbers and short names, so it avoids the most common spreadsheet problems, such as leading zeros or date-like strings. Locale still matters. A spreadsheet set to use commas as decimal marks may split or misread a comma-delimited file. In that case, use the import dialog and specify the delimiter explicitly. Saving the file back from a spreadsheet can also change number formatting or line endings, so keep an untouched original.

Accessibility: a CSV opened as a table in a spreadsheet or data viewer is generally easier to navigate with assistive technology than raw comma-separated text read line by line. No documentation or test results for specific screen readers were available for this article, so check behavior in the tools your readers actually use. Giving the first column a clear header like model, rather than leaving it blank, helps anyone navigating by column header.

Search and editing: plain CSV is fully searchable and diff-friendly. That is a practical advantage over binary formats when the file lives in version control.

Checking that nothing was lost

A round trip is the most direct check. Read the file back with the model column restored as row names, then compare it with the original:

back <- read.csv("mtcars.csv", row.names = "model")
all.equal(back, mtcars)

This should report TRUE. If it doesn't, all.equal lists the differences, which usually point to row-name handling, a changed delimiter, or edits made in a spreadsheet. This check covers your own export only. This article does not assess pre-made mtcars CSV files offered for download elsewhere, so verify any such copy the same way before relying on it.

Bottom line

Exporting mtcars to CSV preserves all 32 rows and 11 numeric columns as portable plain text, provided you turn the row names into a named column. What you give up is metadata, such as the meaning of the 0/1 codes in vs and am, so share that alongside the file. If the data never leaves R, skip the CSV and use the built-in dataset directly.