R code to read and write from/to Excel file

In R, you have multiple options for reading and writing data from/to Excel files. One approach is to use the read.xlsx and write.xlsx functions from the openxlsx package. Alternatively, you can also employ the readxl package for reading data and the writexl package for writing data. Below are examples demonstrating how to use these packages for handling Excel (xls/xlsx) files:

Using the openxlsx package:

# Install and load the openxlsx package
if (!require("openxlsx")){
  install.packages("openxlsx")  
}
library(openxlsx)

# Reading data from an Excel file
data <- read.xlsx("tempfile.xlsx", sheet = "Sheet1")

# Sample data to be written
xls_data <- data.frame(
  Name = c("Apple", "Banana", "Mango", "Pineapple"),
  Age = c(35, 20, 28, 56)
)

# Writing data to a new Excel file
write.xlsx(xls_data, "new_data_file.xlsx")

Using readxl and writexl packages:

# Install and load the readxl and writexl packages
if (!require("readxl")){
  install.packages("readxl")  
}
if (!require("writexl")){
  install.packages("writexl")  
}

library(readxl)
library(writexl)

# Reading data from an Excel file
data <- read_xlsx("tempfile.xlsx", sheet = "Sheet1")

# Sample data to be written
xls_data <- data.frame(
  Name = c("Apple", "Banana", "Mango", "Pineapple"),
  Age = c(35, 20, 28, 56)
)

# Writing data to a new Excel file
write_xlsx(xls_data, "new_data_file.xlsx")

These examples demonstrate two different approaches to reading and writing data from/to Excel files in R. Depending on your specific needs and preferences, you can choose the method that best suits your requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.