• Stars
    star
    107
  • Rank 311,940 (Top 7 %)
  • Language
    R
  • License
    Other
  • Created almost 9 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Avoid the typical working directory pain when using 'knitr'

ezknitr - Avoid the typical working directory pain when using 'knitr'

R Build Status CRAN version

Copyright 2023 Dean Attali. Licensed under the MIT license.

knitr is a popular package for generating dynamic reports in R using the concept of literate programming. ezknitr is an extension of knitr that adds flexibility in several ways and solves a few issues that are commonly encountered with knitr.

One common source of frustration with knitr is that it assumes the directory where the source file lives should be the working directory, which is often not true. ezknitr addresses this problem by giving you complete control over where all the inputs and outputs are, and adds several other convenient features. The two main functions are ezknit() and ezspin(), which are wrappers around knitr's knit() and spin(), used to make rendering markdown/HTML documents easier.

Table of contents

Installation

`ezknitr` is available through both CRAN and GitHub.

To install the CRAN version:

install.packages("ezknitr")

To install the latest developmental version from GitHub:

install.packages("devtools")
devtools::install_github("ropensci/ezknitr")

Overview

If you have a very simple project with a flat directory structure, then `knitr` works great. But even something as simple as trying to knit a document that reads a file from a different directory or placing the output rendered files in a different folder cannot be easily done with `knitr`.

ezknitr improves basic knitr functionality in a few ways. You get to decide:

  • What the working directory of the source file is
    • Default is your current working directory, which often makes more sense than the knitr assumption that the working directory is wherever the input file is
  • Where the output files will go
    • With knitr, all the rendered output files will be generated in the folder you're currently in
  • Where the figures generated in the markdown document will be stored
    • knitr makes it cumbersome to change this directory
  • Any parameters to pass to the source file
    • Useful if you want to run an identical source file multiple times with different parameters

Motivation & simple use case

Assume you have an Rmarkdown file that reads a data file and produces a short report while also generating a figure. Native `knit()` (or `spin()` if you're starting with an R script instead of an Rmd file) works great if you have a flat directory structure like this:
- project/
  |- input.csv
  |- report.Rmd

But what happens if you have a slightly more complex structure? In a real project, you rarely have everything just lying around in the same folder. Here is an example of a more realistic initial directory structure (assume the working directory/project root is set to project/):

- project/
  |- analysis/
     |- report.Rmd
  |- data/
     |- input.csv

Now if you want knitr to work, you'd have to ensure the path to input.csv is relative to the analysis/ directory because that's where the Rmd file is. This is counter-intuitive because most people expect to create paths relative to the working directory/project root (project/ in this case), but knitr will use the analysis/ folder as the working directory. Any code reading the input file needs to use ../data/input.csv instead of data/input.csv.

Other than being confusing, it also means that you cannot naively run the Rmd code chunks manually because when you run the code in the console, your working directory is not set to what knitr will use as the working directory. More specifically, if you try to run the command that reads the input file, your console will look in project/../data/input.csv (which doesn't exist).

A similar problem arises when you want to create files in your report: knitr will create the files relative to where the Rmd file is, rather than relative to the project root.

Another problem with the flat directory structure is that you may want to control where the resulting reports get generated. knitr will create all the outputs in your working directory, and as far as I know there is no way to control that.

ezknitr addresses these issues, and more. It provides wrappers to knit() and spin() that allow you to set the working directory for the input file, and also uses a more sensible default working directory: the current working directory. ezknitr also lets you decide where the output files and output figures will be generated, and uses a better default path for the output files: the directory containing the input file.

Assuming your working directory is currently set to the project/ directory, you could use the following ezknitr command to do what you want:

library(ezknitr)
ezknit(file = "analysis/report.Rmd", out_dir = "reports", fig_dir = "myfigs")

- project/
  |- analysis/
     |- report.Rmd
  |- data/
     |- input.csv
  |- reports/
     |- myfigs/
        |- fig1.png
     |- report.md
     |- report.HTML

We didn't explicitly have to set the working direcory, but you can use the wd argument if you do require a different directory (for example, if you are running this from some build script or from any arbitrary directory). After running ezknit(), you can run open_output_dir() to open the output directory in your file browser if you want to easily see the resulting report. Getting a similar directory structure with knitr is not simple, but with ezknitr it's trivial.

Note that ezknitr produces both a markdown and an HTML file for each report (you can choose to discard them with the keep_md and keep_html arguments).

Use case: using one script to analyze multiple datasets

As an example of a more complex realistic scenario where `ezknitr` would be useful, imagine having multiple analysis scripts, with each one needing to be run on multiple datasets. Being the organizer scientist that you are, you want to be able to run each analysis on each dataset, and keep the results neatly organized. I personally was involved in a few projects requiring exactly this, and `ezknitr` was in fact born for solving this exact issue. Assume you have the following files in your project:
- project/
  |- analysis/
     |- calculate.Rmd
     |- explore.Rmd
  |- data/
     |- human.dat
     |- mouse.dat

We can easily use ezknitr to run any of the analysis Rmarkdowns on any of the datasets and assign the results to a unique output. Let's assume that each analysis script expects there to be a variable named DATASET_NAME inside the script that tells the script what data to operate on. The following ezknitr code illustrates how to achieve the desired output.

library(ezknitr)
ezknit(file = "analysis/explore.Rmd", out_dir = "reports/human",
        params = list("DATASET_NAME" = "human.dat"), keep_html = FALSE)
ezknit(file = "analysis/explore.Rmd", out_dir = "reports/mouse",
        params = list("DATASET_NAME" = "mouse.dat"), keep_html = FALSE)
ezknit(file = "analysis/calculate.Rmd", out_dir = "reports/mouse",
        params = list("DATASET_NAME" = "mouse.dat"), keep_html = FALSE)

- project/
  |- analysis/
     |- calculate.Rmd
     |- explore.Rmd
  |- data/
     |- human.dat
     |- mouse.dat
  |- reports/
     |- human/
        |- explore.md
     |- mouse/
        |- calculate.md
        |- explore.md

Note that this example uses the params = list() argument, which lets you pass variables to the input Rmarkdown. In this case, I use it to tell the Rmarkdown what dataset to use, and the Rmarkdown assumes a DATASET_NAME variable exists. This of course means that the analysis script has an external dependency by having a variable that is not defined inside of it. You can use the set_default_params() function inside the Rmarkdown to ensure the variable uses a default value if none was provided.

Also note that differentiating the species in the output could also have been done using the out_suffix argument instead of the out_dir argument. For example, using out_suffix = "human" would have resulted in an ouput file named explore-human.md.

Experiment with ezknitr

After installing and loading the package (`library(ezknitr)`), you can experiment with `ezknitr` using the `setup_ezknit_test()` or `setup_ezspin_test()` functions to see their benefits. See `?setup_ezknit_test` for more information.

spin() vs knit()

`knit()` is the most popular and well-known function from `knitr`. It lets you create a markdown document from an Rmarkdown file. You can learn more about `knit()` on [the official knitr page](https://yihui.org/knitr/).

spin() is similar, but starts one step further back: it takes an R script as input, creates an Rmarkdown document from the R script, and then proceeds to create a markdown document from it. spin() can be useful in situations where you develop a large R script and want to be able to produce reports from it directly instead of having to copy chunks into a separate Rmarkdown file. You can read more about why I like spin() in the blog post "knitr's best hidden gem: spin".

Using rmarkdown::render()

When the core of this package was developed, none of its functionality was supported in any way by either `knitr` or `rmarkdown`. Over time, `rmarkdown::render()` got some new features that are very similar to features of `ezknitr`. Native support for parameters inside Rmarkdown files using YAML is a big feature which makes the use of `set_default_params()` and the `params` argument of `ezknitr` less important. However, the core problem that `ezknitr` wants to solve is the working directory issue, and this issue has yet to be addressed by `rmarkdown` or `knitr`, which makes `ezknitr` still useful.

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

ropensci_footer

More Repositories

1

drake

An R-focused pipeline toolkit for reproducibility and high-performance computing
R
1,329
star
2

skimr

A frictionless, pipeable approach to dealing with summary statistics
HTML
1,095
star
3

targets

Function-oriented Make-like declarative workflows for R
R
854
star
4

rtweet

🐦 R client for interacting with Twitter's [stream and REST] APIs
R
785
star
5

tabulizer

Bindings for Tabula PDF Table Extractor Library
R
518
star
6

pdftools

Text Extraction, Rendering and Converting of PDF Documents
C++
489
star
7

magick

Magic, madness, heaven, sin
R
440
star
8

visdat

Preliminary Exploratory Visualisation of Data
R
439
star
9

stplanr

Sustainable transport planning with R
R
412
star
10

RSelenium

An R client for Selenium Remote WebDriver
R
332
star
11

rnoaa

R interface to many NOAA data APIs
R
320
star
12

osmdata

R package for downloading OpenStreetMap data
C++
307
star
13

charlatan

Create fake data in R
R
283
star
14

software-review

rOpenSci Software Peer Review.
R
279
star
15

iheatmapr

Complex, interactive heatmaps in R
R
259
star
16

taxize

A taxonomic toolbelt for R
R
250
star
17

rrrpkg

Use of an R package to facilitate reproducible research
248
star
18

elastic

R client for the Elasticsearch HTTP API
R
244
star
19

tesseract

Bindings to Tesseract OCR engine for R
R
236
star
20

qualtRics

Download ⬇️ Qualtrics survey data directly into R!
R
213
star
21

git2r

R bindings to the libgit2 library
R
213
star
22

biomartr

Genomic Data Retrieval with R
R
203
star
23

writexl

Portable, light-weight data frame to xlsx exporter for R
C
202
star
24

rnaturalearth

An R package to hold and facilitate interaction with natural earth map data 🌍
R
191
star
25

googleLanguageR

R client for the Google Translation API, Google Cloud Natural Language API and Google Cloud Speech API
HTML
190
star
26

textreuse

Detect text reuse and document similarity
R
188
star
27

tokenizers

Fast, Consistent Tokenization of Natural Language Text
R
179
star
28

rentrez

talk with NCBI entrez using R
R
178
star
29

piggyback

πŸ“¦ for using large(r) data files on GitHub
R
172
star
30

rcrossref

R client for various CrossRef APIs
R
164
star
31

osmextract

Download and import OpenStreetMap data from Geofabrik and other providers
R
158
star
32

dataspice

🌢️ Create lightweight schema.org descriptions of your datasets
R
155
star
33

tic

Tasks Integrating Continuously: CI-Agnostic Workflow Definitions
R
153
star
34

webchem

Chemical Information from the Web
R
149
star
35

geojsonio

Convert many data formats to & from GeoJSON & TopoJSON
R
148
star
36

MODIStsp

An "R" package for automatic download and preprocessing of MODIS Land Products Time Series
R
147
star
37

rgbif

Interface to the Global Biodiversity Information Facility API
R
146
star
38

tsbox

tsbox: Class-Agnostic Time Series in R
R
146
star
39

DataPackageR

An R package to enable reproducible data processing, packaging and sharing.
R
145
star
40

ghql

GraphQL R client
R
141
star
41

dev_guide

rOpenSci Packages: Development, Maintenance, and Peer Review
R
141
star
42

jqr

R interface to jq
R
139
star
43

osfr

R interface to the Open Science Framework (OSF)
R
136
star
44

osmplotr

Data visualisation using OpenStreetMap objects
R
130
star
45

opencv

R bindings for OpenCV
C++
130
star
46

ssh

Native SSH client in R based on libssh
C
126
star
47

tarchetypes

Archetypes for targets and pipelines
R
116
star
48

RefManageR

R package RefManageR
R
112
star
49

spocc

Species occurrence data toolkit for R
R
109
star
50

hunspell

High-Performance Stemmer, Tokenizer, and Spell Checker for R
C++
106
star
51

crul

R6 based http client for R (made for developers)
R
101
star
52

gistr

Interact with GitHub gists from R
R
101
star
53

spelling

Tools for Spell Checking in R
R
101
star
54

rfishbase

R interface to the fishbase.org database
R
100
star
55

weathercan

R package for downloading weather data from Environment and Climate Change Canada
R
99
star
56

git2rdata

An R package for storing and retrieving data.frames in git repositories.
R
98
star
57

gutenbergr

Search and download public domain texts from Project Gutenberg
R
97
star
58

bib2df

Parse a BibTeX file to a tibble
R
97
star
59

ckanr

R client for the CKAN API
R
97
star
60

rsvg

SVG renderer for R based on librsvg2
C
95
star
61

UCSCXenaTools

πŸ“¦ An R package for accessing genomics data from UCSC Xena platform, from cancer multi-omics to single-cell RNA-seq https://cran.r-project.org/web/packages/UCSCXenaTools/
R
95
star
62

EML

Ecological Metadata Language interface for R: synthesis and integration of heterogenous data
R
94
star
63

nasapower

API Client for NASA POWER Global Meteorology, Surface Solar Energy and Climatology in R
R
93
star
64

cyphr

:shipit: Humane encryption
R
91
star
65

FedData

Functions to Automate Downloading Geospatial Data Available from Several Federated Data Sources
R
91
star
66

av

Working with Video in R
C
88
star
67

mapscanner

R package to print maps, draw on them, and scan them back in
R
87
star
68

opencage

🌐 R package for the OpenCage API -- both forward and reverse geocoding 🌐
R
86
star
69

tidync

NetCDF exploration and data extraction
R
85
star
70

GSODR

API Client for Global Surface Summary of the Day ('GSOD') Weather Data Client in R
R
84
star
71

rzmq

R package for ZMQ
C++
82
star
72

gittargets

Data version control for reproducible analysis pipelines in R with {targets}.
R
80
star
73

openalexR

Getting bibliographic records from OpenAlex
R
80
star
74

bikedata

🚲 Extract data from public hire bicycle systems
R
79
star
75

historydata

Datasets for Historians
R
78
star
76

dittodb

dittodb: A Test Environment for DB Queries in R
R
78
star
77

arkdb

Archive and unarchive databases as flat text files
R
78
star
78

fingertipsR

R package to interact with Public Health England’s Fingertips data tool
R
78
star
79

vcr

Record HTTP calls and replay them
R
77
star
80

rebird

Wrapper to the eBird API
R
77
star
81

smapr

An R package for acquisition and processing of NASA SMAP data
R
77
star
82

nodbi

Document DBI connector for R
R
75
star
83

CoordinateCleaner

Automated flagging of common spatial and temporal errors in biological and palaeontological collection data, for the use in conservation, ecology and palaeontology.
HTML
74
star
84

opentripplanner

An R package to set up and use OpenTripPlanner (OTP) as a local or remote multimodal trip planner.
R
73
star
85

nlrx

nlrx NetLogo R
R
71
star
86

rb3

A bunch of downloaders and parsers for data delivered from B3
R
69
star
87

tidyhydat

An R package to import Water Survey of Canada hydrometric data and make it tidy
R
69
star
88

robotstxt

robots.txt file parsing and checking for R
R
68
star
89

slopes

Package to calculate slopes of roads, rivers and trajectories
R
65
star
90

tradestatistics

R package to access Open Trade Statistics API
R
65
star
91

terrainr

Get DEMs and orthoimagery from the USGS National Map, georeference your images and merge rasters, and visualize with Unity 3D
R
64
star
92

unconf17

Website for 2017 rOpenSci Unconf
JavaScript
64
star
93

NLMR

πŸ“¦ R package to simulate neutral landscape models πŸ”
R
63
star
94

roadoi

Use Unpaywall with R
R
63
star
95

parzer

Parse geographic coordinates
R
63
star
96

tiler

Generate geographic and non-geographic map tiles from R
R
63
star
97

rWBclimate

R interface for the World Bank climate data
R
62
star
98

codemetar

an R package for generating and working with codemeta
R
62
star
99

comtradr

Functions for Interacting with the UN Comtrade API
R
60
star
100

aRxiv

Programmatic interface to the Arxiv API
R
58
star