Quantcast
Channel: Easy Guides
Viewing all articles
Browse latest Browse all 183

Writing Data From R to Excel Files (xls|xlsx)

$
0
0


Previously, we described the essentials of R programming and provided quick start guides for reading and writing txt and csv files using R base functions as well as using a most modern R package named readr, which is faster (X10) than R base functions. We also described different ways for reading data from Excel files into R.


Here, you’ll learn how to export data from R to Excel files (xls or xlsx file formats). We’ll use the xlsx R package.


Writing Data From R to Excel Files (xls|xlsx)

Preleminary tasks

Launch RStudio as described here: Running RStudio and setting up your working directory

Writing Excel files using xlsx package

The xlsx package, a java-based solution, is one of the powerful R packages to read, write and formatExcel files.

Installing and loading xlsx package

  • Install
install.packages("xlsx")
  • Load
library("xlsx")

Using xlsx package

There are two main functions in xlsx package for writing both xls and xlsx Excel files: write.xlsx() and write.xlsx2() [faster on big files compared to write.xlsx function].

The simplified formats are:

write.xlsx(x, file, sheetName = "Sheet1", 
  col.names = TRUE, row.names = TRUE, append = FALSE)

write.xlsx2(x, file, sheetName = "Sheet1",
  col.names = TRUE, row.names = TRUE, append = FALSE)

  • x: a data.frame to be written into the workbook
  • file: the path to the output file
  • sheetName: a character string to use for the sheet name.
  • col.names, row.names: a logical value specifying whether the column names/row names of x are to be written to the file
  • append: a logical value indicating if x should be appended to an existing file.


Example of usage: the following R code will write the R built-in data sets - USArrests, mtcars and iris - into the same Excel file:

library("xlsx")

# Write the first data set in a new workbook
write.xlsx(USArrests, file = "myworkbook.xlsx",
      sheetName = "USA-ARRESTS", append = FALSE)

# Add a second data set in a new worksheet
write.xlsx(mtcars, file = "myworkbook.xlsx", 
           sheetName="MTCARS", append=TRUE)

# Add a third data set
write.xlsx(iris, file = "myworkbook.xlsx",
           sheetName="IRIS", append=TRUE)

Summary


Write data from R to Excel files using xlsx package: write.xlsx(my_data, file = “result.xlsx”, sheetName = “my_data”, append = FALSE).


Infos

This analysis has been performed using R (ver. 3.2.3).


Viewing all articles
Browse latest Browse all 183

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>