How to export an R list to Excel or csv files?

Follow these steps to export an R list object to a Microsoft Excel or csv files on Windows, macOS, Ubuntu or other Linux distribution:

Step 1: Define an R list object

We will start by defining a simple R list object composed of two vectors using the following code:

hr_list <- list(area = c('R', 'Python', 'Power BI'), candidates = c(14, 17, 11))

Step 2: Convert your list to an R DataFrame

Due to the tabular format of Excel (and the csv or tsv formats), we will first convert the list to an R DataFrame. We will use the data.frame constructor as shown below:

hr_df <- data.frame(hr_list)

Step 3: Define a file location

Next we will define a location in our file system in which we will host the csv or Excel file we will import our list into.

xlsx_path = 'hr.xlsx'
csv_path  = 'hr.csv'

Step 4: Export your data to Excel or csv file

Important Note: to save our data into Excel we will be using openxlsx, a 3rd party R package, which needs to be installed into your R development environment (i use RStudio).

You might first want to ensure that openxlsx is installed and install it if it is missing from your system by running the following code:

if (!require(openxlsx)) {
  install.packages("openxlsx")
}

Now we can save the data into the Excel or csv files.

# import into Excel
library(openxlsx)
write.xlsx(hr_df, xlsx_path)

# import into the csv
write.csv(hr_df, csv_path, row.names = FALSE)

Export R list to multiple Excel worksheets

If you have a list of DataFrames you can easily them into multiple Excel worksheets. The basic trick is to loop through your DataFrame list, and use the openxslx package to write each DataFrame into a new Excel Sheet.

Related: How to write a text file object using the R language?

FAQ

Are there other packages that can be used to export R lists and vectors?

In this tutorial, we used openxlsx. In addition the writexl and xlsx packages are used to write R constructs (including DataFrames) to Excel.

How do i know if my R installation includes the openxlsx package?

In RStudio, use the require() function to verify that your package is installed:

require(openxlsx)

If the value TRUE is returned then the package is installed.