Site icon R-bloggers

From R to excel: Part 1

[This article was first published on ZAHIER NASRUDIN, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
< section id="introduction" class="level2">

Introduction

Welcome welcome.

In this blog post, we will be exploring:

  1. How to export multiple data frames into a single Excel file with multiple sheets using the writexl and openxlsx packages

By the end of this post, you & I should have a solid understanding of how to export multiple data frames into 1 excel file (.xlsx)

< section id="purpose" class="level2">

Purpose

Why do you need to export your R output to Excel?

  1. Data Sharing: Excel is a widely used tool for data analysis and reporting.

  2. Further Analysis: Some users might want to perform additional analyses or calculations on the exported data using Excel’s functions, pivot tables, or other features.

  3. User Preference: For some tasks or audiences/stakeholders, Excel might be the preferred tool due to its user-friendly interface or specific features.

< section id="how-to" class="level2">

How-to

< section id="load-library" class="level3">

Load library

We will first load the dplyr library:

library(dplyr)
< section id="data-sets" class="level3">

Data sets

For the data frames, we will use datasets available from the dplyr package.

Here are the datasets available in dplyr:

However, for this, we will focus only just four of them:

band_instruments (3 rows and 2 columns)



band_members (3 rows and 2 columns)



star_wars (87 rows and 14 columns)



storms (19,066 rows and 13 columns)


< section id="export-writexl" class="level3">

Export (writexl)

I will demonstrate two methods for exporting to an Excel file: using the writexl and openxlsx packages

library(writexl)

excel_list <- list("Instruments" = band_instruments,
                   "Members" = band_members,
                   "Star Wars" = starwars,
                   "Storms" = storms)


write_xlsx(excel_list, "file_with_sheets_version1.xlsx")


If you prefer not to format the header (no bold header), you may include format_headers = FALSE:

write_xlsx(excel_list, "file_with_sheets_version1.xlsx", format_headers = FALSE)


< section id="export-openxlsx" class="level3">

Export (openxlsx)

library(openxlsx)

write.xlsx(excel_list, "file_with_sheets_version2.xlsx")



And there you have it! Now you can send the file to stakeholders who prefer Excel.

To leave a comment for the author, please follow the link and comment on their blog: ZAHIER NASRUDIN.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Exit mobile version