27 Jun 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
[code lang = “R”]library(devtools)
package.skeleton(list = c(‘fun1’, ‘fun2’), name = ‘mypkg’)
# mypkg is your package name[/code]
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.
[code]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[/code]
Second, edit the mypkg.RD file, which you find in the folder “man”, opening it in a text editor:
[code]\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)
}[/code]
Check your package in R, change the working directory to your package’s directory
[code lang=”R”]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[/code]
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
[code lang = “R”]devtools::install_github(“yourgithubname/mypkg”) # maybe use , force = TRUE
# Check your function
fun1()[/code]
[divider top=”30″ bottom=”10″ style=”linedcenter”]
Step 3 for local usage
In the Windows command line navigate to your current working directory (here: …\user\mypkg) using
[code lang = “DOS .bat”]cd user
cd mypkg[/code]
Then enter
[code lang = “DOS .bat”]R CMD build mypkg
R CMD check mypkg_1.o.tar.gz
R CMD INSTALL –build mypkg REM[/code]
The first line generates a tar.gz for cran, the last line gets a local windows binary zip file
Install the package
[code lang = “DOS .bat”]R CMD INSTALL mypkg_0.1.tar.gz[/code]
The Windows command line is to be found like this: go tot he Windows search bar > type ‘cmd’ > hit enter > a Shell script opens.