knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

tor

CRAN status Codecov test coverage R-CMD-check R-CMD-check

tor (to-R) helps you to import multiple files at once. For example:

Installation

Install tor from CRAN with:

install.packages("tor")

Or install the development version from GitHub with:

# install.packages("devtools")
devtools::install_github("maurolepore/tor")

Example

library(tor)

withr::local_options(readr.show_col_types = FALSE)

list_*(): Import multiple files from a directory into a list

All functions default to importing files from the working directory.

dir()

list_csv()

Often you will specify a path to read from.

# Helpes create paths to examples
tor_example()

(path_rds <- tor_example("rds"))
dir(path_rds)

list_rds(path_rds)

You may read all files with a particular extension.

path_mixed <- tor_example("mixed")
dir(path_mixed)

list_rdata(path_mixed)

Or you may read specific files matching a pattern.

list_rdata(path_mixed, regexp = "[.]RData", ignore.case = FALSE)

list_any() is the most flexible function. You supply the function to read with.

(path_csv <- tor_example("csv"))
dir(path_csv)

list_any(path_csv, read.csv)

It understands lambda functions and formulas (powered by rlang).

# Use the pipe (%>%)
library(magrittr)

(path_rdata <- tor_example("rdata"))
dir(path_rdata)

path_rdata %>%
  list_any(function(x) get(load(x)))

# Same
path_rdata %>%
  list_any(~ get(load(.x)))

Pass additional arguments via ... or inside the lambda function.

path_csv %>%
  list_any(readr::read_csv, skip = 1)

path_csv %>%
  list_any(~ read.csv(., stringsAsFactors = FALSE))

It also provides the arguments regexp, ignore.case, and invert to pick specific files in a directory (powered by fs).

path_mixed <- tor_example("mixed")
dir(path_mixed)

path_mixed %>%
  list_any(~ get(load(.)), "[.]Rdata$", ignore.case = TRUE)

path_mixed %>%
  list_any(~ get(load(.)), regexp = "[.]csv$", invert = TRUE)

load_*(): Load multiple files from a directory into an environment

All functions default to importing files from the working directory and into the global environment.

# The working directory contains .csv files
dir()

load_csv()

# Each file is now available as a dataframe in the global environment
csv1
csv2

rm(list = ls())

You may import files from a specific path.

(path_mixed <- tor_example("mixed"))
dir(path_mixed)

load_rdata(path_mixed)

ls()
rda

You may import files into a specific environment.

e <- new.env()
ls(e)

load_rdata(path_mixed, envir = e)

ls(e)

For more flexibility use load_any() with a function able to read one file of the format you want to import.

dir()

load_any(".", .f = readr::read_csv, regexp = "[.]csv$")

# The data is now available in the global environment
csv1
csv2

Related projects

Two great packages to read and write data are rio and io.

Information



maurolepore/tor documentation built on July 17, 2024, 12:03 a.m.