R Programming language - R Read and Write xlsx

‮/:sptth‬/www.theitroad.com

In R programming language, you can read and write Excel files in the XLSX format using the read.xlsx() and write.xlsx() functions respectively. These functions require the xlsx package to be installed.

Reading XLSX Files

The read.xlsx() function reads an XLSX file and returns a data frame object. Here's an example:

# Load the xlsx package
library(xlsx)

# Read an XLSX file
mydata <- read.xlsx("mydata.xlsx", sheetIndex = 1)

# View the first few rows of the data
head(mydata)

In this example, we first load the xlsx package using the library() function. We then use the read.xlsx() function to read an XLSX file called mydata.xlsx and store the resulting data frame in the mydata variable. We use the sheetIndex argument to specify which sheet to read. By default, read.xlsx() assumes that the first sheet should be read.

Writing XLSX Files

The write.xlsx() function writes a data frame to an XLSX file. Here's an example:

# Write a data frame to an XLSX file
write.xlsx(mydata, "mydata.xlsx", sheetName = "Sheet1", row.names = FALSE)

In this example, we use the write.xlsx() function to write the mydata data frame to an XLSX file called mydata.xlsx. The sheetName argument is set to "Sheet1" to specify the name of the worksheet. The row.names argument is set to FALSE to exclude row names from the output.

By default, write.xlsx() uses the openxlsx package to write XLSX files. If you prefer to use a different package, you can set the package argument to the name of the desired package. For example, to use the xlsx package instead, you would set package = "xlsx":

# Write a data frame to an XLSX file using the xlsx package
write.xlsx(mydata, "mydata.xlsx", sheetName = "Sheet1", row.names = FALSE, package = "xlsx")

In this example, we use the write.xlsx() function with the package argument set to "xlsx" to write the mydata data frame to an XLSX file using the xlsx package.