Overview
RStudio v1.1 introduces support for custom, user-defined project templates. Project templates can be used to create new projects with a pre-specified structure.
Project templates can be accessed through the New Project… wizard. All registered project templates are made available within the New Directory portion of the wizard:
R packages are the primary vehicle through which RStudio project templates are distributed. Package authors can provide a small bit of metadata describing the template functions available in their package – RStudio will discover these project templates on start up, and make them available in the New Project… dialog.
Example
We’ll use the ptexamples package to illustrate how a project template can be defined. This package exports a project template that is presented like so from the New Project… wizard:
After the user clicks Create Project, a new project will be created, and the hello_world()
template function will be called to initialize the project. Here’s what the IDE looks like after calling this template function with the aforementioned inputs:
If you want to try using this project template yourself, try installing the package with:
devtools::install_github("rstudio/ptexamples")
and then accessing it from the New Project… wizard.
Let’s dive in and see how exactly the ptexamples
package defines and exports this project template.
Defining the Template Function
The ptexamples
package contains a function, hello_world()
, intended to be used as a project template. The function has the signature:
hello_world <- function(path, ...) {
# ensure path exists
dir.create(path, recursive = TRUE, showWarnings = FALSE)
# generate header for file
header <- c(
"# This file was generated by a call to 'ptexamples::hello_world()'.",
"# The following inputs were received:",
""
)
# collect inputs and paste together as 'Parameter: Value'
dots <- list(...)
text <- lapply(seq_along(dots), function(i) {
key <- names(dots)[[i]]
val <- dots[[i]]
paste0(key, ": ", val)
})
# collect into single text string
contents <- paste(
paste(header, collapse = "\n"),
paste(text, collapse = "\n"),
sep = "\n"
)
# write to index file
writeLines(contents, con = file.path(path, "INDEX"))
}
When this function is invoked by RStudio, it will receive the path
as the path to the newly created project, as well as arguments as received from its input widgets. This function simply collects its inputs, and echos them to a file called INDEX
in the newly-created project path.