4 min read•august 9, 2024
Excel files are a common data format in business and research. This section covers importing Excel data into R using the package, which offers functions to read various Excel file types and customize the import process.
We'll also explore exporting data from R to Excel using the package. This includes creating workbooks, adding worksheets, and applying formatting to make your Excel outputs professional and easy to read.
readxl
package provides functions to read Excel files directly into Rreadxl
package using install.packages("readxl")
commandlibrary(readxl)
before using its functions[read_excel](https://www.fiveableKeyTerm:read_excel)()
function serves as the primary tool for importing Excel dataread_excel("path/to/file.[xlsx](https://www.fiveableKeyTerm:xlsx)")
reads the entire first sheet
argument (sheet name or number)read_excel("file.xlsx", sheet = "Sales Data")
imports the "Sales Data" sheet[range](https://www.fiveableKeyTerm:Range)
argument to import specific cell rangesread_excel("file.xlsx", range = "B2:D50")
imports cells B2 through D50sheet
and range
for precise data selection[col_names](https://www.fiveableKeyTerm:col_names)
argument controls whether first row is treated as column namescol_names = FALSE
to import all rows as data, useful for headerless filesna
argument in read_excel()
specifies values to be treated as missingread_excel("file.xlsx", na = c("N/A", "Missing"))
converts "N/A" and "Missing" to NAcol_types
argument to manually specify column data typescol_types = c("text", "numeric", "date")
sets types for first three columnsguess_max
argument determines how many rows to use for type guessingguess_max
for more accurate type detection in large datasetstrim_ws
argument removes leading and trailing whitespace from cell valuesopenxlsx
package provides tools for creating and writing Excel filesinstall.packages("openxlsx")
and load using library(openxlsx)
[write.xlsx](https://www.fiveableKeyTerm:write.xlsx)()
function quickly exports data frames to Excel fileswrite.xlsx(data, file = "output.xlsx")
saves data to "output.xlsx"createWorkbook()
function initializes a new Workbook objectaddWorksheet()
functionwriteData()
function writes data to specific worksheets within the WorkbooksaveWorkbook()
saves the Workbook object as an Excel file on diskaddWorksheet(wb, "Sheet1", tabColor = "red")
adds a red-tabbed worksheetsetColWidths()
functionsetRowHeights()
functionaddStyle()
and style()
functionsmergeCells()
function for creating headers or grouping datainsertImage()
functionwriteFormula()
functionconditionalFormatting()
functioninsertPlot()
functionprotectWorksheet()
and protectWorkbook()
dataValidation()
functioncreateNamedRegion()
and dataValidation()
freezePane()
functionis.character()
, is.numeric()
, is.logical()
help identify data typesclass()
function in R to determine the imported data type from Excel