---
description: How to Export Data from R In this tutorial, we will learn how to export data from R environment to different formats. To export data to the hard drive, you need the file path and an extension. First o
title: How to Export Data from R to CSV &#038; Excel
image: https://www.guru99.com/images/export-data-from-r-csv-excel.png
---

[Skip to content](#main)

**⚡ Smart Summary**

Export Data from R covers writing a data frame to CSV, Excel, SPSS, SAS, STATA, and native R formats, then pushing the same file to Google Drive or Dropbox. Every export follows one pattern: a function, a data frame, and a destination path.

- 📁 **Destination First:** getwd() reports the working directory, and any relative filename is written there unless a full path is supplied.
- 📄 **CSV Export:** write.csv(df, “file.csv”) is the universal option, and write.csv2() switches to semicolon separators.
- 📗 **Excel Export:** write.xlsx() from the xlsx package requires a working Java installation on the machine.
- 🔄 **Statistical Software:** The haven package writes SPSS, SAS, and STATA files with write\_sav(), write\_sas(), and write\_dta().
- 💾 **Native Formats:** saveRDS() stores a single object and save() stores several, both preserving factor levels and attributes exactly.
- ☁️ **Cloud Upload:** googledrive and rdrop2 authenticate once per session, then upload, download, and delete files directly from R.

Read More

![Export Data from R CSV Excel](https://www.guru99.com/images/export-data-from-r-csv-excel.png)

## How to Export Data from R

In this tutorial, we will learn how to export data from R environment to different formats.

To export data to the hard drive, you need the file path and an extension. First of all, the path is the location where the data will be stored. In this tutorial, you will see how to store data on:

- The hard drive
- Google Drive
- Dropbox

Second, R can write the data out in many formats. This tutorial covers the essential file extensions:

- csv
- xlsx
- RDS
- SAS
- SPSS
- STATA

Every export follows the same shape: one function call, a data frame, and a destination path.

## Export to Hard drive

To begin with, you can save the data directly into the working directory. The following code prints the path of your working directory:

```
directory <- getwd()
directory
```

**Output:**

```
## [1] "/Users/15_Export_to_do"
```

Unless you supply a full path, every file is written into that working directory. The default differs by system, typically the user home folder on macOS and Linux and the Documents folder on Windows, but getwd() always tells you the current value. Change it with setwd(), or simply pass a full path to the write function.

```
setwd("/Users/USERNAME/Downloads")
```

### Create data frame

First, build a small data frame: the mean of mpg and disp grouped by gear from the mtcars dataset.

```
library(dplyr)
df <-mtcars %>%
    select(mpg, disp, gear) %>%
    group_by(gear) %>%
    summarize(mean_mpg = mean(mpg), mean_disp = mean(disp))
df

```

**Output:**

```
## # A tibble: 3 x 3
##	gear mean_mpg mean_disp
##	<dbl>	<dbl>	<dbl>
## 1	3 16.10667  326.3000
## 2 	4 24.53333  123.0167
## 3	5 21.38000  202.4800
```

The table contains three rows and three columns. You can create a CSV file with the function write.csv in R.

## How to Export a DataFrame to a CSV File in R

The basic syntax of write.csv in R to Export the DataFrame to CSV in R:

```
write.csv(df, path)
arguments
-df: Dataset to save. Need to be the same name of the data frame in the environment.
-path: A string. Set the destination path. Path + filename + extension i.e. "/Users/USERNAME/Downloads/mydata.csv" or the filename + extension if the folder is the same as the working directory
```

Example:

```
write.csv(df, "table_car.csv")
```

Code Explanation

- write.csv(df, “table\_car.csv”): Create a CSV file in the hard drive:
  - df: name of the data frame in the environment
  - “table\_car.csv”: Name the file table\_car and store it as csv

**Note**: write.csv2() writes the same file using a semicolon as the field separator and a comma as the decimal mark, which is the convention in much of continental Europe.

```
write.csv2(df, "table_car.csv")
```

**Note**: For pedagogical purpose only, we created a function called open\_folder() to open the directory folder for you. You just need to run the code below and see where the csv file is stored. You should see a file named table\_car.csv.

```
# Run this code to create the function
open_folder <-function(dir){
	if (.Platform['OS.type'] == "windows"){
	shell.exec(dir)  
	} else {
	system(paste(Sys.getenv("R_BROWSER"), dir))
  }
}
# Call the function to open the folder
open_folder(directory)
```

## How to Export a DataFrame to an Excel File in R

Exporting to Excel is straightforward on Windows and slightly trickier on macOS. Both use the xlsx library, and the difference is only in the installation, because xlsx depends on Java. Java must be present on the machine before the package will load.

**Windows users**

On Windows, install the library directly with conda:

```
conda install -c r r-xlsx
```

Once the library is installed, write.xlsx() creates a new Excel workbook in the working directory:

```
library(xlsx)
write.xlsx(df, "table_car.xlsx")
```

If you are a Mac OS user, you need to follow these steps:

- Step 1: Install the latest version of Java
- Step 2: Install library rJava
- Step 3: Install library xlsx

**Step 1)** You could download Java from official Oracle site and install it.

You can go back to Rstudio and check which version of Java is installed.

```
system("java -version")
```

Any recent Java release works. If the command reports nothing, Java is not installed and the xlsx package will fail to load.

**Step 2)** You need to install rjava in R. We recommended you to install R and Rstudio with Anaconda. Anaconda manages the dependencies between libraries. In this sense, Anaconda will handle the intricacies of rJava installation.

First of all, you need to update conda and then install the [library](https://anaconda.org/r/r-rjava). You can copy and paste the next two lines of code in the terminal.

```
conda update conda
conda install -c r r-rjava

```

Next, open rjava in Rstudio

```
library(rJava)
```

**Step 3)** Finally, it is time to install xlsx. Once again, you can use [conda](https://anaconda.org/r/r-xlsx) to do it:

```
conda install -c r r-xlsx
```

Just as the windows users, you can save data with the function write.xlsx()

```
library(xlsx)
```

**Output:**

```
## Loading required package: xlsxjars
```

```
write.xlsx(df, "table_car.xlsx")
```

## Exporting Data from R to Different Software

Exporting data to different software is as simple as importing them. The library “haven” provides a convenient way to export data to

- spss
- sas
- stata

First of all, import the library. If you don’t have “haven”, you can go [here](https://anaconda.org/conda-forge/r-haven) to install it.

```
library(haven)
```

### SPSS file

Below is the code to export the data to SPSS software:

```
write_sav(df, "table_car.sav")
```

### SAS file

Just as simple as spss, you can export to sas

```
write_sas(df, "table_car.sas7bdat")
```

### STATA file

Finally, haven library allows writing .dta file.

```
write_dta(df, "table_car.dta")
```

**Don't Miss:**

- [Lists in R Programming: How to Create & Select Elements](https://www.guru99.com/r-lists-create-select.html)
- [R Sort Data Frame: order() Function with Example](https://www.guru99.com/r-sort-data-frame.html)
- [Pearson & Spearman Correlation Matrix in R with Example](https://www.guru99.com/r-pearson-spearman-correlation.html)
- [GLM in R: Generalized Linear Model & Logistic Regression](https://www.guru99.com/r-generalized-linear-model.html)

## How to Export Data to R Native Formats

If you want to keep the object inside R rather than hand it to another program, use one of the two native formats. save() writes one or more named objects into a .RData file:

```
save(df, file ='table_car.RData')
```

The alternative is saveRDS(), which stores exactly one object and lets the reader choose its name on the way back in:

```
# One object, name chosen at read time
saveRDS(df, file = "table_car.rds")
my_data <- readRDS("table_car.rds")

# Several objects, original names restored
save(df, directory, file = "workspace.RData")
load("workspace.RData")
```

| Criteria | saveRDS() / readRDS() | save() / load() |
| --- | --- | --- |
| Objects per file | Exactly one | One or many |
| Object name on reload | You choose it | Restored as saved |
| Overwrites the environment | No | Yes, silently |
| Usual extension | .rds | .RData |

Prefer saveRDS() in scripts, because load() can silently overwrite an existing object of the same name. Both formats keep factor levels, ordering, and attributes intact, which CSV cannot do.

You can check the files created above in the present working directory

[![Export Data from R to STATA File]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD1.png)

## Interact with the Cloud Services

Last but not least, [R](https://www.guru99.com/r-tutorial.html) is equipped with fantastic libraries to interact with the cloud computing services. The last part of this tutorial deals with export/import files from:

- Google Drive
- Dropbox

**Note**: This part of the tutorial assumes you have an account with Google and Dropbox. If not, you can quickly create one for – Google Drive: https://accounts.google.com/SignUp?hl=en – Dropbox: [https://www.dropbox.com/h](https://guru99.live/QgBTOR)

## Google Drive

You need to install the library googledrive to access the function allowing to interact with Google Drive.

The library is not yet available at Anaconda. You can install it with the code below in the console.

```
install.packages("googledrive")
```

and you open the library.

```
library(googledrive)
```

For non-conda user, installing a library is easy, you can use install.packages(‘NAME OF PACKAGE’) with the package name in quotes inside the parentheses. R installs it into the first location returned by .libPaths().

### Upload to Google Drive

To upload a file to Google drive, you need to use the function drive\_upload().

Each time you restart Rstudio, you will be prompted to allow access tidyverse to Google Drive.

The basic syntax of drive\_upload() is

```
drive_upload(file, path = NULL, name = NULL)
arguments:
- file: Full name of the file to upload (i.e., including the extension)
- path: Location of the file- name: You can rename it as you wish. By default, it is the local name.
```

After you launch the code, you need to confirm several questions

```
drive_upload("table_car.csv", name = "table_car")
```

**Output:**

```
## Local file: 
## * table_car.csv 
## uploaded into Drive file: 
## * table_car: 1hwb57eT-9qSgDHt9CrVt5Ht7RHogQaMk 
## with MIME type: 
## * text/csv
```

You type 1 in the console to confirm the access

[![Google Drive]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD2.png)

Then, you are redirected to Google API to allow the access. Click Allow.

[![Google Drive]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD3.png)

Once the authentication is complete, you can quit your browser.

[![Google Drive]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD4.png)

In the Rstudio’s console, you can see the summary of the step done. Google successfully uploaded the file located locally on the Drive. Google assigned an ID to each file in the drive.

[![Google Drive]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD5.png)

You can see this file in Google Spreadsheet.

```
drive_browse("table_car")
```

**Output:**

You will be redirected to Google Spreadsheet

[![Google Drive]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD6.png)

### Import from Google Drive

Downloading by file ID is the reliable route. If you know the file name, retrieve its ID first:

**Note**: Depending on your internet connection and the size of your Drive, it takes times.

```
x <-drive_get("table_car")
as_id(x)
```

[![Google Drive]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD7.png)

You stored the ID in the variable x. The function drive\_download() allows downloading a file from Google Drive.

The basic syntax is:

```
drive_download(file, path = NULL, overwrite = FALSE)
arguments:
- file:  Name or id of the file to download
-path: Location to download the file. By default, it is downloaded to the working directory and the name as in Google Drive
-overwrite = FALSE: If the file already exists, don't overwrite it. If set to TRUE, the old file is erased and replaced by the new one.
```

You can finally download the file:

```
download_google <- drive_download(as_id(x), overwrite = TRUE)
```

Code Explanation

- drive\_download(): Function to download a file from Google Drive
- as\_id(x): Use the ID to browse the file in Google Drive
- overwrite = TRUE: If file exists, overwrite it, else execution halted To see the name of the file locally, you can use:

**Output:**

[![Google Drive]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD8.png)

The file is stored in your working directory. Remember to add the file extension before opening it in R. You can create the full name with the function paste() (i.e. table\_car.csv)

```
google_file <-download_google$local_path
google_file
path <-paste(google_file, ".csv", sep = "")
google_table_car <-read.csv(path)
google_table_car
```

**Output:**

```
##   X gear mean_mpg mean_disp
## 1 1    3 16.10667  326.3000
## 2 2    4 24.53333  123.0167
## 3 3    5 21.38000  202.4800

```

Finally, you can remove the file from your Google drive.

```
## remove file
drive_find("table_car") %>%drive_rm()
```

**Output:**

[![Google Drive]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD9.gif)

Deletion is processed asynchronously by Google, so the file may take a moment to disappear.

## Export to Dropbox

R interacts with Dropbox via the rdrop2 library. The library is not available at Anaconda as well. You can install it via the console

```
install.packages('rdrop2')
```

```
library(rdrop2)
```

You grant temporary access to Dropbox with your credentials. Once authenticated, R can create, remove, upload and download files in your Dropbox.

First of all, you need to give access to your account. The credentials are cached during all session.

```
drop_auth()
```

You will be redirected to Dropbox to confirm the authentication.

[![Export to Dropbox]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD10.png)

You will get a confirmation page. You can close it and return to R

[![Export to Dropbox]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD11.png)

You can create a folder with the function drop\_create().

- drop\_create(‘my\_first\_drop’): Create a folder in the first branch of Dropbox
- drop\_create(‘First\_branch/my\_first\_drop’): Create a folder inside the existing First\_branch folder.

```
drop_create('my_first_drop')
```

**Output:**

[![Export to Dropbox]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD12.png)

In DropBox

[![Export to Dropbox]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD13.png)

To upload the .csv file into your Dropbox, use the function drop\_upload().

Basic syntax:

```
drop_upload(file, path = NULL, mode = "overwrite")
arguments:
- file: local path
- path: Path on Dropbox 
- mode = "overwrite":  By default, overwrite an existing file. If set to `add`, the upload is not completed.

```

```
drop_upload('table_car.csv', path = "my_first_drop")
```

**Output:**

[![Export to Dropbox]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD14.png)

At DropBox

[![Export to Dropbox]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD15.png)

You can read the csv file from Dropbox with the function drop\_read\_csv()

```
dropbox_table_car <-drop_read_csv("my_first_drop/table_car.csv")
dropbox_table_car
```

**Output:**

```
##   X gear mean_mpg mean_disp
## 1 1    3 16.10667  326.3000
## 2 2    4 24.53333  123.0167
## 3 3    5 21.38000  202.4800

```

When you are done using the file and want to delete it. You need to write the path of the file in the function drop\_delete()

```
drop_delete('my_first_drop/table_car.csv')
```

**Output:**

[![Export to Dropbox]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD16.png)

It is also possible to delete a folder

```
drop_delete('my_first_drop')
```

**Output:**

[![Export to Dropbox]()](https://www.guru99.com/images/r_programming/032918_0502_RExportingD17.png)

## Exporting Data from R: Function Reference

Every export function used in this tutorial is listed below:

| Library | Objective | Function |
| --- | --- | --- |
| base | Export csv | write.csv() |
| xlsx | Export excel | write.xlsx() |
| haven | Export spss | write\_sav() |
| haven | Export sas | write\_sas() |
| haven | Export stata | write\_dta() |
| base | Export R objects | save() / saveRDS() |
| googledrive | Upload Google Drive | drive\_upload() |
| googledrive | Open in Google Drive | drive\_browse() |
| googledrive | Retrieve file ID | drive\_get(as\_id()) |
| googledrive | Download from Google Drive | drive\_download() |
| googledrive | Remove file from Google Drive | drive\_rm() |
| rdrop2 | Authentication | drop\_auth() |
| rdrop2 | Create a folder | drop\_create() |
| rdrop2 | Upload to Dropbox | drop\_upload() |
| rdrop2 | Read csv from Dropbox | drop\_read\_csv() |
| rdrop2 | Delete file from Dropbox | drop\_delete() |

## FAQs

💾 What is the difference between saveRDS() and save() in R?

saveRDS() stores a single object and readRDS() lets you assign it to any name. save() stores several objects and load() restores their original names, which can silently overwrite variables already in your environment.

📄 Why does write.csv() add an extra column of row numbers?

By default write.csv() writes row names as an unnamed first column. Pass row.names = FALSE to suppress it, otherwise reimporting the file produces a stray X column.

📗 How can you export to Excel without installing Java?

Use writexl::write\_xlsx() or openxlsx::write.xlsx(). Both write .xlsx files in pure R with no Java dependency, which avoids the rJava setup that the xlsx package requires.

🤖 Which export format suits AI and machine learning pipelines?

Use RDS or Parquet rather than CSV. Both preserve column types and factor levels, so a training dataset reloads identically. CSV silently converts types and is a common source of irreproducible model results.

🧠 Can AI assistants help debug file export errors in R?

Yes. AI assistants can diagnose permission errors, wrong working directories, and missing Java for the xlsx package. Always confirm the destination with getwd() before trusting a suggested path.

#### Summarize this post with:

ChatGPTPerplexityGrokGoogle AI

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.**

##### Sign up for the newsletter

Subscribe for Free

You have successfully subscribed.  
Please check your inbox.

![AI-Newsletter]() Chosen by over **350,000+** professionals

[Scroll to top](#wrapper)

×

Search for:

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/export-data-from-r-csv-excel.png","url":"https://www.guru99.com/images/export-data-from-r-csv-excel.png","width":"700","height":"250","caption":"Export Data from R - CSV &amp; Excel","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/r-exporting-data.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/r-programming","name":"R Programming"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/r-exporting-data.html","name":"How to Export Data from R to CSV &#038; Excel"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/r-exporting-data.html#webpage","url":"https://www.guru99.com/r-exporting-data.html","name":"How to Export Data from R to CSV &#038; Excel","dateModified":"2026-07-27T16:14:02+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/export-data-from-r-csv-excel.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/r-exporting-data.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/evelyn","name":"Evelyn Clarke","description":"I'm Evelyn Clarke, an AI Research Scientist specializing in machine learning and natural language processing, dedicated to advancing the field responsibly.","url":"https://www.guru99.com/author/evelyn","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/evelyn-clarke-author-120x120.png","url":"https://www.guru99.com/images/evelyn-clarke-author-120x120.png","caption":"Evelyn Clarke","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"R Programming","headline":"How to Export Data from R to CSV &#038; Excel","description":"How to Export Data from R In this tutorial, we will learn how to export data from R environment to different formats. To export data to the hard drive, you need the file path and an extension. First o","keywords":"R, Programming","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/evelyn","name":"Evelyn Clarke"},"dateModified":"2026-07-27T16:14:02+05:30","image":{"@id":"https://www.guru99.com/images/export-data-from-r-csv-excel.png"},"copyrightYear":"2026","name":"How to Export Data from R to CSV &#038; Excel","subjectOf":[{"@type":"HowTo","name":"How to Export a Data from R to Excel File","description":"Export data from R to Excel is trivial for Windows users and trickier for Mac OS users.","step":[{"@type":"HowToStep","name":"Step 1) Install the latest version of Java","text":"You could download Java from the official Oracle site and install it. You can go back to Rstudio and check which version of Java is installed.","url":"https://www.guru99.com/r-exporting-data.html#step1"},{"@type":"HowToStep","name":"Step 2) Install library rJava","text":"You need to install rjava in R. We recommend you to install R and Rstudio with Anaconda.","url":"https://www.guru99.com/r-exporting-data.html#step2"},{"@type":"HowToStep","name":"Step 3) Install library xlsx","text":"Finally, it is time to install xlsx. Once again, you can use conda to do it. Just as the windows users, you can save data with the function write.xlsx()","url":"https://www.guru99.com/r-exporting-data.html#step3"}]},{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the difference between saveRDS() and save() in R?","acceptedAnswer":{"@type":"Answer","text":"saveRDS() stores a single object and readRDS() lets you assign it to any name. save() stores several objects and load() restores their original names, which can silently overwrite variables already in your environment."}},{"@type":"Question","name":"Why does write.csv() add an extra column of row numbers?","acceptedAnswer":{"@type":"Answer","text":"By default write.csv() writes row names as an unnamed first column. Pass row.names = FALSE to suppress it, otherwise reimporting the file produces a stray X column."}},{"@type":"Question","name":"How can you export to Excel without installing Java?","acceptedAnswer":{"@type":"Answer","text":"Use writexl::write_xlsx() or openxlsx::write.xlsx(). Both write .xlsx files in pure R with no Java dependency, which avoids the rJava setup that the xlsx package requires."}},{"@type":"Question","name":"Which export format suits AI and machine learning pipelines?","acceptedAnswer":{"@type":"Answer","text":"Use RDS or Parquet rather than CSV. Both preserve column types and factor levels, so a training dataset reloads identically. CSV silently converts types and is a common source of irreproducible model results."}},{"@type":"Question","name":"Can AI assistants help debug file export errors in R?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI assistants can diagnose permission errors, wrong working directories, and missing Java for the xlsx package. Always confirm the destination with getwd() before trusting a suggested path."}}]}],"@id":"https://www.guru99.com/r-exporting-data.html#schema-24863","isPartOf":{"@id":"https://www.guru99.com/r-exporting-data.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/r-exporting-data.html#webpage"}}]}
```
