15.1 C
London
Friday, July 5, 2024
HomeRImport & Export Data in RHow to Export a Data Frame to a CSV File in R...

How to Export a Data Frame to a CSV File in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

Suppose we have the following data frame in R:

#create data frame
df #view data frame
df

  team points assists
1    A     78      12
2    B     85      20
3    C     93      23
4    D     90       8
5    E     91      14

There are three common ways to export this data frame to a CSV file in R:

1. Use write.csv from base R

If your data frame is reasonably small, you can just use the write.csv function from base R to export it to a CSV file.

When using this method, be sure to specify row.names=FALSE if you don’t want R to export the row names to the CSV file.

write.csv(df, "C:\Users\Bob\Desktop\data.csv", row.names=FALSE)

2. Use write_csv from reader package

An even faster way to export a data frame to a CSV file is with the write_csv function from the reader package. This is about 2x faster than write.csv and it never writes the row names from the data frame to a CSV file.

library(readr)

write_csv(df, "C:\Users\Bob\Desktop\data.csv")

3. Use fwrite from data.table package

Yet a faster way (and a recommended method for large datasets) to export a data frame to a CSV file is with the fwrite function from the data.table package. This function is about 2x faster than the write_csv method.

library(data.table)

fwrite(df, "C:\Users\Bob\Desktop\data.csv")

Note that in each example we used double backslashes (\) in the file path to avoid the following common error:

Error: 'U' used without hex digits in character string starting ""C:U"

The Output

Each of the three methods above produce an identical CSV file. If we open this file with Excel, here’s what it looks like:

Export data frame to a CSV file in R

And if we open the CSV file with a text reader like Notepad, here’s what it looks like:

Export data frame to CSV in R

Related: How to Import CSV Files into R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories