logo

How to create R-Packages

Do you need some functions over and over again? Tired of sourcing them to multiple projects?

Wrap functions in an R package (Windows)

Here is how you wrap two functions — fun1 and fun2 — into your own little R package, called mypkg, in three Steps. (And even how to get them on GitHub).

Step 1

Functions fun1 and fun2 should exist in your current R session. In R, type

library(devtools)
package.skeleton(list = c('fun1', 'fun2'), name = 'mypkg')
# mypkg is your package name

Step 2

A new folder “mypkg” appears in your current R working directory (getwd()). In this folder, edit two files. First, edit the DESCRIPTION file , opening it with a text editor. If your code needs other packages like dplyr add Imports, else not.

Package: mypkg
Type: Package
Title: mypkg
Version: 1.0
Date: 2018-06-27
Author: Yourname1 Yourname2
Maintainer: Yourname1 Yourname2 <you@youremail.com>
Description: The package contains functions fun1 and fun2.
Imports: dplyr
License: GPL-3

Second, edit the mypkg.RD file, which you find in the folder “man”, opening it in a text editor:

\name{fun1}
\alias{fun1}
\title{The title of my function fun1}
\usage{
fun1(obs, pred = NULL, n = NULL, type = "binary",
saturated = FALSE, discount = 0, eps = 1e-05)
}

Check your package in R, change the working directory to your package’s directory

setwd('../mypkg')
check()
# Thows a lot of code
# It will flag "ERROR" if something is substantially wrong
# It will show some warnings
# For now, ignore the
# warnings

Step 3: Packge usage on GitHub

Make a new github repository, ideally it is named like your package. Commit all folders and files in your package (man, R, DESCRIPTION, NAMESPACE) to this repository. To install your package in R

devtools::install_github("yourgithubname/mypkg") # maybe use , force = TRUE
# Check your function
fun1()

Step 3 for local usage

In the Windows command line navigate to your current working directory (here: …\user\mypkg) using

cd user
cd mypkg

Then enter

R CMD build mypkg
R CMD check mypkg_1.o.tar.gz
R CMD INSTALL –build mypkg REM

The first line generates a tar.gz for cran, the last line gets a local windows binary zip file

Install the package
R CMD INSTALL mypkg_0.1.tar.gz

The Windows command line is to be found like this: go tot he Windows search bar > type ‘cmd’ > hit enter > a Shell script opens.

  • Share

Leave a reply

Your email address will not be published. Required fields are marked *