Monday, April 11, 2016

Create R package from scratch

I often forget how to create an R package from scratch, and how best to save it for future use and editing. Here is an example on creating a package named purr:

Create a package skeleton:
setwd("parent_directory")
library(devtools)
create("purr")

Open a new file in RStudio and create one or more functions, e.g.:
purr <- function() {print("Rrrrrrrrr Rrrrrrrr Rrrrrrr")}  

Save this file as parent_directory/R/purr.R.

Create a manual for the function: Create a new folder parent_directory/man/. Open a new file in RStudio and copy-paste this code:
\name{purr}
\alias{purr}
\encoding{latin1}
\title{Purr like a cat}
\description{
  Function to make R purr like a cat.
}
\usage{
  purr()
}
%\arguments{
%  \item(}{}
%}
\details{
  Not much.
}
\value{
  The function prints a character string.
}
\references{
  \url{https://en.wikipedia.org/wiki/Purr}
}
\examples{
  purr()
}
\keyword{purr} 

Next, save this file as parent_directory/man/purr.Rd.

Finally, test usability by building, installing and using the package:

build("purr")
install("purr")
library(purr)
purr()

Alternatively, if you want to check if the package will pass R CMD check if you want to submit the package to CRAN, run:
check("purr")

No comments:

Post a Comment