Reading data in R depends on the file type:
Using read.table() or
read.csv(): If your data is in a plain text file
(such as a CSV file), you can use the read.table() or
read.csv() function to import it into R.
Using read.xlsx() from the
openxlsx package: If your data is in an Excel
file, you can use the read.xlsx() function from the
openxlsx package to import it.
install.packages("openxlsx")
library(openxlsx)
data <- read.xlsx("filename.xlsx")
readRDS(): If your data is saved
in R’s binary format (.rds), you can use the
readRDS() function to import it.data <- readRDS("filename.rds")
readr package provides functions like
read_csv() for faster and more flexible CSV reading.install.packages("readr")
library(readr)
data <- read_csv("filename.csv")
To read a database file in R, use the DBI package along
with a specific database driver package such as RSQLite for
SQLite databases or RMySQL for MySQL databases.
DBI package along with the
specific database driver package for your database type (e.g.,
RSQLite, RMySQL, ROracle,
etc.).# Install DBI package
install.packages("DBI")
# Install specific database driver package (e.g., RSQLite)
install.packages("RSQLite")
# Load packages
library(DBI)
library(RSQLite)
dbConnect() function to establish a connection to the
database. You’ll need to provide the appropriate connection details such
as the database type, host, port, username, password, and database
name.# Connect to SQLite database
con <- dbConnect(RSQLite::SQLite(), dbname = "path/to/database/file.sqlite")
dbGetQuery() function.# Execute SQL query
result <- dbGetQuery(con, "SELECT * FROM tablename")
# Print the result
print(result)
dbDisconnect() function.# Close the connection
dbDisconnect(con)
Replace "path/to/database/file.sqlite" with the path to
your actual database file and "SELECT * FROM tablename"
with your SQL query.