There are two main packages that you can use to read Excel files in R:
- readxl is a newer package that is designed to be more consistent with other data import packages in R. It supports both Excel 97-2003 (.xls) and Excel 2007+ (.xlsx) formats.
- xlsx is an older package that is still widely used. It supports only Excel 2007+ (.xlsx) formats.
To read an Excel file in R, you will need to install the appropriate package and then use the `read_excel()` or `read.xlsx()` function. The following code shows how to read an Excel file into R using the `readxl` package:
library(readxl)
# Read the Excel file
df <- read_excel("my_data.xlsx")
# Print the data frame
print(df)
This code will read the Excel file `my_data.xlsx` into a data frame called `df`. The `print()` function will then print the data frame to the console.
You can also use the `read_excel()` or `read.xlsx()` function to read a specific sheet from an Excel file. For example, the following code will read the first sheet from the Excel file `my_data.xlsx` into a data frame called `df`:
library(readxl)
# Read the first sheet from the Excel file
df <- read_excel("my_data.xlsx", sheet = 1)
# Print the data frame
print(df)
You can also use the `read_excel()` or `read.xlsx()` function to specify a range of cells to read. For example, the following code will read the cells A1:C10 from the Excel file `my_data.xlsx` into a data frame called `df`:
library(readxl)
# Read the cells A1:C10 from the Excel file
df <- read_excel("my_data.xlsx", range = "A1:C10")
# Print the data frame
print(df)
download.file()
# Check if the `data` directory exists
if (!file.exists("data")) {
# Create the `data` directory
dir.create("data")
}
# Set the file URL
fileUrl <- "https://example.com/data.xlsx"
# Download the file
download.file(fileUrl, destfile = "./data/data.xlsx")
# Get the date of download
dateDownloaded <- date()