forked from dewittpe/drug-r-pkg-talk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple-r-packages.Rnw
671 lines (599 loc) · 18.6 KB
/
simple-r-packages.Rnw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
% ---------------------------------------------------------------------------- %
% file: simple-r-packages.Rnw
% author: Peter DeWitt <[email protected]>
%
% presentation on building simple R packages for the Denver R Users Group
% Meetup on 18 June 2015
%
% ---------------------------------------------------------------------------- %
\documentclass{beamer}
\setbeamersize{text margin left=5pt,text margin right=5pt}
\usefonttheme{serif}
\usepackage{verbatim}
\author{Peter DeWitt\\[email protected]}
\date{18 June 2015}
\title{An Introduction to Creating R Packages}
\subtitle{Denver R Users Group\\www.meetup.com/DenverRUG}
<<"setup", include = FALSE>>=
options(stringsAsFactors = FALSE)
options(width = 62)
library(knitr)
# library(devtools)
opts_chunk$set(fig.align = "center",
fig.pos = "!htp",
size = "footnotesize",
cache = FALSE,
dev = "pdf",
error = TRUE,
tidy = FALSE)
@
% ---------------------------------------------------------------------------- %
% ---------------------------------------------------------------------------- %
\begin{document}
% ---------------------------------------------------------------------------- %
% Title page
% ---------------------------------------------------------------------------- %
\begin{frame}[fragile]
\maketitle
\end{frame}
\section{Simple Code}
\begin{frame}[fragile]
\frametitle{Common Tasks?}
\begin{itemize}
\item Think about your life in code.
\begin{itemize}
\item How many tasks do you code regularly?
\item How many of these tasks have you created a general function for?
\item How do you reuse code?
\begin{itemize}
\item Rewrite?
\item {\tt helpful-stuff.R}?
\item A package? \end{itemize}
\end{itemize}
\item Let's consider two common tasks for examples:
\begin{enumerate}
\item Report the mean and standard deviation as a formated character
string.
\item Construct a receiver operating curve (ROC) for a logistic regression
model.
\end{enumerate}
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Please don't do this}
<<>>=
data('diamonds', package = 'ggplot2')
mean_price <- mean(diamonds$price)
mean_carat <- mean(diamonds$carat)
mean_depth <- mean(diamonds$depth)
sd_price <- sd(diamonds$price)
sd_carat <- sd(diamonds$carat)
sd_depth <- sd(diamonds$depth)
paste0(formatC(mean_price, digits = 2, format = "f"), " (",
formatC(sd_price, digits = 2, format = "f"), ")")
paste0(formatC(mean_carat, digits = 2, format = "f"), " (",
formatC(sd_carat, digits = 2, format = "f"), ")")
paste0(formatC(mean_depth, digits = 2, format = "f"), " (",
formatC(sd_depth, digits = 2, format = "f"), ")")
@
\end{frame}
\begin{frame}[fragile]
\frametitle{Better, but \ldots}
<<>>=
mean_sd <- function(x) {
m <- mean(x)
s <- sd(x)
paste0(formatC(m, digits = 2, format = "f"), " (",
formatC(s, digits = 2, format = "f"), ")")
}
mean_sd(diamonds$price)
mean_sd(diamonds$carat)
mean_sd(diamonds$depth)
@
\begin{itemize}
\item Good for a one-off project. Documentation? Reuse? Share?
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Create a Package}
\begin{itemize}
\item Well documented, shareable functions.
\item Easy to use on multiple projects.
\item Many very helpful tools exist to make package authorship easy.
\begin{itemize}
\item Thank you, Hadley Wickham, for
\begin{itemize}
\item {\tt devtools} package
\item {\tt roxygen2} package
\item The book {\it R packages} \url{http://r-pkgs.had.co.nz/}
\end{itemize}
\end{itemize}
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Create a Package}
Create the skeleton of an R package.
<<eval = FALSE>>=
devtools::create("mypackage")
@
\begin{alltt}
{\bf mypackage/}
|--{\bf R}
|---DESCRIPTION
|---mypackage.Rproj
`---NAMESPACE
1 directory, 3 files
\end{alltt}
\end{frame}
\begin{frame}[fragile]
\frametitle{Edit the {\tt DESCRIPTION} file}
\begin{itemize}
\item Package Meta Data
\item \url{http://r-pkgs.had.co.nz/description.html}
\end{itemize}
\vspace{0.2in}
{\it Generated File:}
\tiny
\begin{alltt}
Package: mypackage
Title: What the Package Does (one line, title case)
Version: 0.0.0.9000
Authors@R: person("First", "Last", , "[email protected]", role = c("aut", "cre"))
Description: What the package does (one paragraph)
Depends: R (>= 3.2.0)
License: What license is it under?
LazyData: true
\end{alltt}
\normalsize
{\it Edited file:}
\tiny
\begin{alltt}
Package: mypackage
Title: A collection of helper functions
Version: 0.0.0.9000
Authors@R: person("Peter", "DeWitt", , "peter.dewitt@ucdenver", role = c("aut", "cre"))
Description: Commonly used formatting functions. A minimalist set of functions
used to show an example of building an R package.
Depends: R (>= 3.0.2)
License: GPL-2
LazyData: true
\end{alltt}
\end{frame}
\begin{frame}[fragile]
\frametitle{Add R Code}
\begin{itemize}
\item To add R code to your package add a file to the {\tt R/} directory:
\end{itemize}
\begin{alltt}
mypackage/R/mean_sd.R
\end{alltt}
\begin{itemize}
\item Within this file we will author the R code and the corresponding
documention via roxygen comments (prefaced with {\verb|#'|}).
\item The function {\tt devtools::document()} will parse the R file(s) and
populate the needed {\tt man/} files.
\item[]
\item The following slides show the contents of the {\tt
mypackage/R/mean\_sd.R} file. This version was copied from the {\tt
qwraps2} package I'm developing.
\begin{itemize}
\item \url{http://cran.r-project.org/web/packages/qwraps2/}
\item \url{https://github.com/dewittpe/qwraps2}
\end{itemize}
\end{itemize}
\end{frame}
\begin{frame}[fragile, allowframebreaks]
\scriptsize
\begin{verbatim}
#' @title Mean and Standard deviation
#'
#' @description A function for calculating and formatting means and
#' standard deviations.
#'
#' @details
#' Given a numeric vector, \code{mean_sd} will return a character string with
#' the mean and standard deviation. Formating of the output will be extended in
#' future versions.
#'
#' @param x a numeric vector
#' @param digits digits to the right of the decimal point to return in the
#' percentage estimate.
#' @param na_rm if true, omit NA values
#' @param show_n defaults to "ifNA". Other options are "always" or "never".
#' @param denote_sd a character string set to either "pm" or "paren" for reporting
#' 'mean \eqn{\pm} sd' or 'mean (sd)'
#' @param markup latex or markdown
#'
#' @return a character vector of the formatted values
#'
#' @examples
#' set.seed(42)
#' x <- rnorm(1000, 3, 4)
#' mean(x)
#' sd(x)
#' mean_sd(x)
#' mean_sd(x, show_n = "always")
#' mean_sd(x, show_n = "always", denote_sd = "paren")
#'
#' x[187] <- NA
#' mean_sd(x, na_rm = TRUE)
#'
#' @export
mean_sd <- function(x,
digits = getOption("qwraps2_frmt_digits", 2),
na_rm = FALSE,
show_n = "ifNA",
denote_sd = "pm",
markup = getOption("qwraps2_markup", "latex")) {
n <- sum(!is.na(x))
m <- mean(x, na.rm = na_rm)
s <- sd(x, na.rm = na_rm)
if (show_n =="always" | any(is.na(x))) {
rtn <- paste0(frmt(as.integer(n), digits), "; ", frmt(m, digits),
" $\\pm$ ", frmt(s, digits))
} else {
rtn <- paste0(frmt(m, digits), " $\\pm$ ", frmt(s, digits))
}
if (denote_sd == "paren") {
rtn <- gsub("\\$\\\\pm\\$\\s(.*)", "\\(\\1\\)", rtn)
}
if (markup == "markdown") {
rtn <- gsub("\\$\\\\pm\\$", "±", rtn)
}
return(rtn)
}
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\frametitle{Current Directory Structure}
\begin{alltt}
{\bf mypackage/}
|--{\bf R}
| `-- mean\_sd.R
|-- DESCRIPTION
|-- mypackage.Rproj
`-- NAMESPACE
1 directory, 4 files
\end{alltt}
\end{frame}
\begin{frame}[fragile]
\frametitle{Generate the required documentation}
<<eval = FALSE>>=
devtools::document('mypackage')
# Updating mypackage documentation
# Loading mypackage
# First time using roxygen2 4.0 Upgrading automatically...
# Writing NAMESPACE
# Writing mean_sd.Rd
@
\small
\begin{alltt}
{\bf mypackage/}
|--{\bf man}
| `-- mean\_sd.Rd
|--{\bf R}
| `-- mean\_sd.R
|-- DESCRIPTION
|-- mypackage.Rproj
`-- NAMESPACE
2 directory, 5 files
\end{alltt}
\normalsize
The next couple slides show the contents of {\tt mean\_sd.Rd}
\end{frame}
\begin{frame}[fragile, allowframebreaks]
% \frametitle{Generated Files}
\scriptsize
\begin{verbatim}
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/mean_sd.R
\name{mean_sd}
\alias{mean_sd}
\title{Mean and Standard deviation}
\usage{
mean_sd(x, digits = getOption("qwraps2_frmt_digits", 2), na_rm = FALSE,
show_n = "ifNA", denote_sd = "pm", markup = getOption("qwraps2_markup",
"latex"))
}
\arguments{
\item{x}{a numeric vector}
\item{digits}{digits to the right of the decimal point to return in the
percentage estimate.}
\item{na_rm}{if true, omit NA values}
\item{show_n}{defaults to "ifNA". Other options are "always" or "never".}
\item{denote_sd}{a character string set to either "pm" or "paren" for reporting
'mean \eqn{\pm} sd' or 'mean (sd)'}
\item{markup}{latex or markdown}
}
\value{
a character vector of the formatted values
}
\description{
A function for calculating and formatting means and
standard deviations.
}
\details{
Given a numeric vector, \code{mean_sd} will return a character string with
the mean and standard deviation. Formating of the output will be extended in
future versions.
}
\examples{
set.seed(42)
x <- rnorm(1000, 3, 4)
mean(x)
sd(x)
mean_sd(x)
mean_sd(x, show_n = "always")
mean_sd(x, show_n = "always", denote_sd = "paren")
x[187] <- NA
mean_sd(x, na_rm = TRUE)
}
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\begin{itemize}
\item I've added code for a formating function {\tt frmt()} to the example
package too.
\item Evaluated {\tt devtools::document('mypackage/')} and
\end{itemize}
\begin{alltt}
{\bf mypackage/}
|--{\bf man}
| |-- frmt.Rd
| `-- mean\_sd.Rd
|--{\bf R}
| |-- frmt.R
| `-- mean\_sd.R
|-- DESCRIPTION
|-- mypackage.Rproj
`-- NAMESPACE
2 directory, 7 files
\end{alltt}
\end{frame}
\begin{frame}[fragile]
\frametitle{Building the Package}
<<eval=FALSE>>=
devtools::build("mypackage/")
# 'usr/lib/R/bin/R' --vanilla CMD build \
# '/home/dewittpe/drug--r-pkg-talk/mypackage' \
# --no-resave-data --noanual
#
# * checking for file '/home/dewittpe/drug-r-pkg-talk/mypackage/DESCRIPTION' ... OK
# * preparing 'mypackage':
# * checking DESCRIPTION meta-information ... OK
# * checking for LF line-endings in source and make files
# * checking for empty or unneeded directories
# * building 'mypackage_0.0.0.9000.tar.gz'
#
# [1] "/home/dewittpe/drug-r-pkg-talk/mypackage_0.0.0.9000.tar.gz"
@
\begin{itemize}
\item Can also be done from the command line via {\tt R CMD build}.
\item {\tt devtools::install()} is calling {\tt R CMD build}.
\item Send the {\tt .tar.gz} files to colaborators to install the package on
their machine(s).
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Install the Package}
\begin{itemize}
\item Do so via {\tt R CMD INSTALL}, or
\item {\tt install.packages()}, or
\item {\tt devtools::install()}.
\end{itemize}
\small
<<eval=FALSE>>=
# use with_libpaths() to change the library the package is installed too
devtools::with_libpaths("r-dev", devtools::install("mypackage/"))
## Installing mypackage
## '/usr/lib/R/bin/R' --vanilla CMD INSTALL \
## '/home/dewittpe/drug-r-pkg-talk/mypackage' \
## --library='/home/dewittpe/drug-r-pkg-talk/r-dev' --install-tests
##
## * installing *source* package ‘mypackage’ ...
## ** R
## ** preparing package for lazy loading
## ** help
## *** installing help indices
## ** building package indices
## ** testing if installed package can be loaded
## * DONE (mypackage)
@
\end{frame}
\begin{frame}[fragile]
\frametitle{Check the install}
<<>>=
rm(list = ls())
data("diamonds", package = "ggplot2")
# errors... package not loaded and attached
mean_sd(diamonds$price, markup = "markdown")
# Load and attach the package
library(package = "mypackage", lib.loc = "r-dev/")
mean_sd(diamonds$price)
mean_sd(diamonds$price, markup = "markdown")
@
\end{frame}
\begin{frame}[fragile]
\frametitle{Using Code from Other Packages}
\begin{itemize}
\item First, you'll need to edit the {\tt DESCRIPTION} file for your
package.
\begin{itemize}
\item {\tt Imports} packages (loaded by namespace),
\item {\tt Depends} on is `poor form.'
\end{itemize}
\item Second, the {\tt ::} operator is your friend.
\begin{itemize}
\item Requires the package to be loaded.
\item Does not require attaching a package.
\item Robust to end user's attached, and order of attaching, packages.
\end{itemize}
\item Next slide: updated {\tt DESCRIPTION} file.
\item We'll look at the file {mypackage/R/qroc.R}
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Updated {\tt DESCRIPTION} file}
\scriptsize
\begin{verbatim}
Package: mypackage
Title: A collection of helper functions
Version: 0.0.0.9000
Authors@R: person("Peter", "DeWitt", , "peter.dewitt@ucdenver", role = c("aut", "cre"))
Description: Commonly used formatting functions. A minimalist set of functions
used to show an example of building an R package.
Depends: R (>= 3.0.2)
License: GPL-2
LazyData: true
Imports:
ggplot2
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\frametitle{Impact of calling code form other packages via {\tt ::}}
We can plot a ROC curve, but cannot change the theme to black and white
becuase {\tt ggplot2} is not attached.
<<out.width="0.25\\textwidth">>=
fit1 <- glm(formula = I(price > 2800) ~ cut * color,
data = diamonds,
family = binomial())
qroc(fit1)
qroc(fit1) + theme_bw()
@
\end{frame}
\begin{frame}[fragile]
<<out.width="0.25\\textwidth">>=
library(ggplot2)
qroc(fit1) + theme_bw()
@
<<eval=FALSE>>=
# The same graphic could be generated via
qroc(fit1) + ggplot2::theme_bw()
# with or without attaching ggplot2
@
\end{frame}
\begin{frame}[fragile]
\frametitle{Compiled Code}
\begin{itemize}
\item Do you have some C++ code that you'd like to have access to in R?
\item {\tt Rcpp} will be very helpful!
\item {\tt Rcpp.package.skeleton()} and the Rcpp-package vignette for more
details.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Package Checks}
\begin{itemize}
\item Use {\tt devtools::check()}, or
\item {\tt R CMD check}.
\item[]
\item Getting a package, espeically your first one, to pass the check is
difficult.
\item Best documentation, and notes to help prevent common errors:
\url{http://r-pkgs.had.co.nz/check.html}
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Packages on github.com}
\begin{itemize}
\item There are many R packages on github.
\begin{itemize}
\item Development versions of what is on CRAN.
\item Some only available on github.
\end{itemize}
\item Version control, releases, issue tracking, \ldots
\item Others can install your package via
<<eval = FALSE>>=
devtools::install_github()
@
\item Barebone websites
\item {\it R packages} has a great chapter on git:
\url{http://r-pkgs.had.co.nz/git.html}
\item {\tt devtools} has functions for installing from \url{bitbucket.org}
and other hosting sites.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Submitting to CRAN}
If you are going to submit your pakage to CRAN, the package needs to meet
the CRAN Repository Policy
\url{http://cran.r-project.org/web/packages/policies.html} and there is a
web form for submission, \url{http://xmpalantir.wu.ac.at/cransubmit/}.
\begin{itemize}
\item Check your package via
\begin{itemize}
\item {\tt R CMD check}, or
\item {\tt devtools::check()}.
\end{itemize}
\item ERRORS, WARNINGS, and NOTES will be returned.
\begin{itemize}
\item Correct all ERRORS before submitting
\item Correct as many WARNINGS as possible (preferably all)
\item Address all NOTES
\end{itemize}
\item CRAN reviewers are mean, blunt, pompus, \ldots (All of which
are well deserved and earned traits)
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{My Favorite NOTE}
% 'no visible binding for global variable' must be resolved before submitting to
% CRAN. It would be good form to fix these issues whetherornot subitting to
% CRAN.
<<eval = F>>=
# This function, in a package, will result in two NOTES
# R CMD check
#
# * checking R code for possible problems ... NOTE
# aplot: no visible binding for global variable ‘xvec’
# aplot: no visible binding for global variable ‘yvec’
aplot <- function(x, y) {
this_data <- data.frame(xvec = mtcars[, x], yvec = mtcars[, y])
ggplot2::ggplot(this_data) +
ggplot2::aes(x = xvec, y = yvec) +
ggplot2::geom_point()
}
# Passes the R CMD check
aplot <- function(x, y) {
this_data <- data.frame(xvec = mtcars[, x], yvec = mtcars[, y])
ggplot2::ggplot(this_data) +
ggplot2::aes_string(x = "xvec", y = "yvec") +
ggplot2::geom_point()
}
@
\end{frame}
\begin{frame}[fragile]
\frametitle{My Suggestions}
\begin{itemize}
\item Read {\it R Packages} by Hadley Wickham,
\url{http://r-pkgs.had.co.nz/}
\item Thanks to {\tt devtools} writting a package for personal use is
reasonable for all levels of R users.
\item Write simple, short functions. Many robust, simple, and specific
functions is preferable to a few complex functions.
\item Writting a package will help you learn a lot about how R works in
general. It will help improve your coding overall.
\item Host on github.com
\item Use TravisCI
\item It's FUN!
\item Can be lucritive.
\item Having a package on CRAN is a nice `feather in your hat.'
\item[]
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Closing}
\begin{itemize}
\item Matt will extend this talk by showing some specific development steps
in RStudio.
\item[]
\item Side note: We are always looking for speakers. Any one, from novice
to expert, is welcome to give a talk, even a short one.
\end{itemize}
\vspace{0.5in}
\begin{center}
Thank you for listening.
Questions?
\end{center}
\end{frame}
\end{document}