How to 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:\\Users\\Bob\\Desktop\\data.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

Leave a Reply

Your email address will not be published.