3.5 批量导入数据
library(tidyverse)read_list <- function(list_of_datasets, read_func) {
read_and_assign <- function(dataset, read_func) {
dataset_name <- as.name(dataset)
dataset_name <- read_func(dataset)
}
# invisible is used to suppress the unneeded output
output <- invisible(
sapply(list_of_datasets,
read_and_assign,
read_func = read_func, simplify = FALSE, USE.NAMES = TRUE
)
)
# Remove the extension at the end of the data set names
names_of_datasets <- c(unlist(strsplit(list_of_datasets, "[.]"))[c(T, F)])
names(output) <- names_of_datasets
return(output)
}批量导入文件扩展名为 .csv 的数据文件,即逗号分割的文件
data_files <- list.files(path = "path/to/csv/dir",
pattern = ".csv", full.names = TRUE)
print(data_files)相比于 Base R 提供的 read.csv 函数,使用 readr 包的 read_csv 函数可以更快地读取csv格式文件,特别是在读取GB级数据文件时,效果特别明显。
list_of_data_sets <- read_list(data_files, readr::read_csv)使用 tibble 包的glimpse函数可以十分方便地对整个数据集有一个大致的了解,展示方式和信息量相当于 str 加 head 函数
tibble::glimpse(list_of_data_sets)