15 How to create a package
15.1 What is an R package?
An R package is a folder that contains required files and sub-folders. In RStudio, it is easy to create an R package.
15.2 Two handy tools
devtoolsroxygen2
15.3 The procedure
Step 1: Create the “structure”, which is an empty folder containing required although empty sub-folders and files, in RStudio. file>new project…>package
Step 2: Write R files and save them in the R folder. An example:
#' find key information about a dataframe
#'
#' This function allows you to find key information about a dataframe
#' @param a_df a dataframe
#' @keywords key info; dataframe
#' @export
#' @author Lingyun (Larry) Zhang \email{lyzhang10@gmail.com}
#' @examples
#' temp_df <-
#' data.frame(a = 1:10,
#' b = NA,
#' e = c(letters[1:8], NA, NA))
#' x <- find_df_key_info(temp_df)
#' @importFrom magrittr %>%
find_df_key_info <- function(a_df)
{re_df <-
data.frame(vari_names = names(a_df)) %>%
dplyr::mutate(type = purrr::map_chr(a_df, typeof),
no_of_unique_rows = purrr::map_int(a_df, function(x) length(unique(x))),
no_of_rows = dim(a_df)[1],
no_of_NAs = purrr::map_int(a_df, function(x) sum(is.na(x))))
return(re_df)
}- Step 3: Run the following R code
library(devtools)
library(roxygen2)
document()- Step 4: Work on
DESCRIPTIONfile. An example:
Package: dfexplorer
Type: Package
Title: 'dfexplorer' for explore new dataframe
Version: 0.1.0
Author: Lingyun (Larry) Zhang
Maintainer: Lingyun (Larry) Zhang <lyzhang10@gmail.com>
Description: This package contains functions for explore "new" data in a dataframe
Imports:
dplyr,
magrittr,
purrr
License: GPL-3
Encoding: UTF-8
LazyData: true
RoxygenNote: 6.1.1
Step 5: Build the package by clicking on the
Buildbutton and …- Step 6: Version control—link to a repo in Github
- initialize the project. Tools>Version Control>…
- stage and commit
- create a repo under your Github account
- set up connection by clicking
Gitbutton; then clicking on the “two purple boxes and a white square” in the Git pane …. (Key parameters: new branch namemaster; remote nameorigin. Reference: section 17.5.3 on https://happygitwithr.com/existing-github-last.html) - commit and push