🔌 Kết nối dữ liệu trong R từ nhiều nguồn

Trong phân tích dữ liệu thực tế, bước kết nối & nhập dữ liệu (Data Ingestion) là bước đầu tiên và rất quan trọng.
Ngôn ngữ R cung cấp nhiều gói và công cụ mạnh mẽ để kết nối đến nhiều loại nguồn dữ liệu khác nhau, từ file cục bộ đến cơ sở dữ liệu và web API.


📁 1. Kết nối từ file phẳng: .csv, .xlsx, .xls, .txt

✅ CSV

library(readr)
data_csv <- read_csv("du_lieu/data.csv")

✅ Excel (.xlsx / .xls)


library(readxl)
data_excel <- read_excel("du_lieu/data.xlsx", sheet = 1)

✅ Text / TSV

data_txt <- read_delim("data.txt", delim = "\t")

📂 2. Đọc dữ liệu từ một thư mục chứa nhiều file

✅ Thư mục chứa nhiều file CSV

library(readr)
library(dplyr)

files <- list.files("folder_csv", pattern = "\\.csv$", full.names = TRUE)
data_all <- files %>% lapply(read_csv) %>% bind_rows()

✅ Thư mục chứa nhiều file Excel


library(readxl)
library(purrr)

files <- list.files("folder_excel", pattern = "\\.xlsx$", full.names = TRUE)
data_all <- map_dfr(files, read_excel)

🧾 3. Đọc dữ liệu từ file PDF (dạng bảng)

library(tabulizer)

# Cần Java, hỗ trợ tốt trên Windows/macOS

data_pdf <- extract_tables("du_lieu/file.pdf")[[1]] %>% as.data.frame()

🌐 4. Kết nối từ Google Sheets

library(googlesheets4)

sheet_url <- "https://docs.google.com/spreadsheets/d/1abcXYZ..."
data_gsheet <- read_sheet(sheet_url)

✅ Bạn cần đăng nhập Google lần đầu (OAuth2), sau đó R sẽ ghi nhớ

🗃 5. Kết nối dữ liệu từ SharePoint / OneDrive

➤ Cách đơn giản:

Lấy link chia sẻ dạng CSV từ Excel Online

Dùng read_csv() như với link web:

url <- "https://sharepoint.company.com/sites/.../File.csv?web=1"
data_sharepoint <- read_csv(url)

✅ Hoặc dùng gói httr nếu cần đăng nhập, hoặc sử dụng API Graph (nâng cao)

🧩 6. Kết nối từ SQL Server (qua ODBC)

library(DBI)
library(odbc)

con <- dbConnect(odbc(),
                 Driver = "SQL Server",
                 Server = "server_name",
                 Database = "db_name",
                 UID = "username",
                 PWD = "password",
                 Port = 1433)

data_sql <- dbGetQuery(con, "SELECT * FROM SalesData")
dbDisconnect(con)

🧩 7. Kết nối từ Oracle Database


library(DBI)
library(ROracle)

drv <- dbDriver("Oracle")
con <- dbConnect(drv, username = "user", password = "pass", dbname = "XE")

data_oracle <- dbGetQuery(con, "SELECT * FROM KHACHHANG")
dbDisconnect(con)

⚠️ Cần cài đặt client Oracle & cấu hình TNSNAME trên máy

🌐 8. Kết nối từ API (RESTful JSON/XML)

library(httr)
library(jsonlite)

res <- GET("https://api.example.com/data")
json_data <- content(res, as = "text")
data_api <- fromJSON(json_data, flatten = TRUE)

✅ Có thể dùng thêm headers cho token xác thực:


res <- GET("https://api.example.com/data",
           add_headers(Authorization = "Bearer YOUR_TOKEN"))

✅ Tổng kết bảng hỗ trợ kết nối

Nguồn dữ liệu Gói hỗ trợ Hàm chính

.csv, .txt readr read_csv(), read_delim() .xlsx, .xls readxl read_excel()

Folder file

readr, purrr list.files(), map_dfr()

PDF (bảng)

tabulizer extract_tables()

Google Sheets

googlesheets4 read_sheet()

SharePoint / Online

readr / httr read_csv(url)

SQL Server

DBI, odbc dbConnect(), dbGetQuery()

Oracle

ROracle dbConnect(), dbGetQuery()

REST API (JSON/XML)

httr, jsonlite GET(), fromJSON()

📌 Gợi ý tốt nhất cho quản lý dữ liệu lớn

Quản lý kết nối SQL bằng .env hoặc cấu hình riêng

Dùng arrow, duckdb, vroom nếu xử lý tập lớn

Ghi log dữ liệu đầu vào nếu dùng trong báo cáo định kỳ

📁 Tài liệu tham khảo

https://r4ds.hadley.nz/

https://db.rstudio.com

https://googlesheets4.tidyverse.org

https://cran.r-project.org/web/packages/httr