How can I export a data frame to an Excel file in R?

Exporting a data frame to an Excel file in R is a simple and efficient way to transfer data from R to Excel. To do so, first make sure to install and load the “xlsx” package in R. Then, use the “write.xlsx” function to save the data frame as an Excel file. This function allows for customization of the file name, sheet name, and whether or not to include row names. By following these steps, the data frame can be easily exported and seamlessly integrated into Excel for further analysis or visualization.

Export a Data Frame to an Excel File in R


The easiest way to export a data frame to an Excel file in R is to use the write_xlsx() function from the writexl package

This function uses the following syntax:

write_xlsx(x, path)

where:

  • x: Name of the data frame to export
  • path: A file name to write to

This tutorial provides an example of how to use this function to export a data frame to an Excel file in R.

Example: Export Data Frame to Excel File in R

Suppose we have the following data frame in R:

#create data frame
df <- data.frame(team=c('A', 'B', 'C', 'D', 'E'),
                 points=c(78, 85, 93, 90, 91),
                 assists=c(12, 20, 23, 8, 14))

#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

The following code shows how to export this data frame to an Excel file in R:

#install and load writexl package
install.packages('writexl')library(writexl)write_xlsx(df, 'C:UsersBobDesktopdata.xlsx')

Note that 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 data frame is now available as an Excel file on my desktop. Here’s what the file looks like:

Export data frame to Excel file in R

Additional Resources

How to Import Excel Files into R
How to Import CSV Files into R
How to Export a Data Frame to a CSV File in R

x