May 15, 2020

How to Add a Vignette to a Package in RStudio



R package vignettes are user-friendly ways to demo your package's capabilities. They can also be helpful documentation for your own reference when modifying the package in the future  -- "what was I thinking there?"

The easiest way to create a vignette in RStudio is using File | New File | R Markdown | From Template | Package Vignette (HTML). Write your RMarkdown document. {Note: Be sure to copy the "title" of your vignette to where "Vignette Title" shows in the section below:
vignette: >
  %\VignetteIndexEntry{Vignette Title}
}

After that, build your package. But if you use the typical procedure for developing a package in RStudio, your vignette will not show up. [Pulling hair out] Let me explain.

My typical procedure for building package myPackage in RStudio is to use two menu items in the Build pane
  • Check, then
  • Install and Restart
Check makes sure everything checks out correctly. This includes processing vignettes in the myPackage/vignettes directory, which you can see in multiple areas of Check's output in that pane:
...
-  installing the package to build vignettes
v  creating vignettes (7.4s)
...
* checking files in 'vignettes' ... OK
...
* checking for unstated dependencies in vignettes ... OK
* checking package vignettes in 'inst/doc' ... OK
* checking re-building of vignette outputs ... OK
...
When R CMD check succeeded appears at the bottom of that output, click Install and Restart in the Build pane again and myPackage will be recompiled, reloaded, and ready to go ... all except for the vignettes, because when you look for them, they won't be there:
> browseVignettes("myPackage")
No vignettes found by browseVignettes("myPackage")
> 
It turns out, according to RStudio's slightly-outdated online documentation this behavior is to be expected because, presumably, developers don't want to worry about vignettes in the typical code/Install-and-Restart/re-code development cycle [I get that]; to wit: 
RStudio’s “Build & reload” does not build vignettes to save time.
{Note: "Build and reload" has been renamed "Install and Restart" in today's RStudio Version 1.2.5042.}

In any event, the correct workflow was pointed out in 2018 by user2554330 in a stackoverflow post
No. Go to the Build pane, then in the "More" dropdown, choose "Build Source Package". This will create a file with extension .tar.gz, which you can distribute to others. You install it using "Packages | Install | Install from... | Package Archive file". – user2554330 Mar 25 '18 at 19:10
That worked great. Thank you RStudio for software that tends to simply get it done one way or another, and thank you user2554330 for explaining how to get it done for vignettes.

Apr 24, 2020

New R Package 'foo' -- Updated


RUN THESE LINES IN AN R SESSION ...

# Navigate to where you want your folder to be located
setwd("C:/Users/chief/Documents/Github")
# Run create_package in 'usethis' package and read below what happens
usethis::create_package("foo")
# Messages show up in the console including this line
# ✔ Opening 'foo/' in new RStudio session
WHEN SWITCHED TO THE NEW SESSION, RUN THESE LINES / EXECUTE THESE STEPS ...

# Add a test environment and add your first test script
usethis::use_testthat()
setwd("R") # this is where you need to be
usethis::use_test("firsttest") # edit your first test; close
setwd("..")
# That will create a file 'test-firsttest.R' in foo\tests\testthat
# LICENSE...not necessary, but Check Package will issue warning without it
#  Open DESCRIPTION -- just click in RStudio
#  Assuming GPL-3 ...
#  Replace
#   License: What license it uses
# with
#   License: GPL-3 | file LICENSE
#
# Put a LICENSE file in the root. In RStudio, File, New File, Text File
#   "GPL3 License file"
# as the sole contents works for me, or the license here:
https://www.gnu.org/licenses/gpl-3.0.txt
# File, Save As, LICENSE
# roxygenise to create help files, run tests, etc.
roxygen2::roxygenise()
# Your package is ready to be checked.
# In RStudio Menu, go to Build, Check (as in "check package integrity")
# All should check ok, no errors, no problems.
# Write some code.
# Then roxygen2::roxygenise() and Build, Check
# Repeat
# When ready to build the actual package
# In RStudio Menu, go to Build, Install and Restart


That's it.

Note: Whenever you add new functionality from another package, don't forget to change the DESCRIPTION file -- roxygen can't do that for you.

May 30, 2019

How to start a new package with testing in R

# Navigate where you want your folder to be located setwd("C:/Users/chief/Documents/Github") # Assumes usethis is installed usethis::create_package("foo") # Say yes or no to next (annoying) popup window, it doesn't matter. # Add a test environment setwd("foo") usethis::use_testthat() # Add your first test function to at least get something in that folder. # Go to foo\tests\testthat # and add this file with a name that begins with 'test_' context("foo") library(foo) test_that("I'm testing something", { # do something with your code expect_equal(1:4, 1:4) }) # After writing a function with roxygen comments, roxygenize your package roxygen2::roxygenise() # Then click "Check" under RStudio's Build tab # You may get a warning about "Non-standard license specification". # To clean that up, see below. # Keep changing your code and roxygenizing until your package checks out clean.
# Once no errors, click "Install and Restart" next to "Check" and you're done.

You're Done! # Don't forget! # The only thing roxygen doesn't handle is, # whenever you add new functionality from another package, # you have have to change DESCRIPTION. License Assuming you just go GPL Open DESCRIPTION Replace "What license it uses" with GPL-3 | file LICENSE and put a file named LICENSE in the same directory as DESCRIPTION. For me, this file content sufficed Something about GPL but the GNU community would probably prefer you used the one here https://www.gnu.org/licenses/gpl-3.0.txt

Apr 12, 2017

CAS RPM: Installing & running Rattle in RStudio

At the Ratemaking and Product Management (RPM) seminar of the Casualty Actuarial Society (CAS) in San Diego last month, Linda Brobeck, Peggy Brinkmann, and yours truly gave a concurrent session on a machine learning technique called decision tree analysis. See the DSPA-2 session -- and other sessions -- at this link. Technical issues precluded showing the video of  installing and running Rattle within RStudio. Thus this post.

As Peggy notes, installing and running Rattle takes only three "commands" in R:
  install.packages("rattle", dependencies=c('Depends', "Suggests"))
  library(rattle)
  rattle()

Although not necessary, the "Suggests" option above can avoid Rattle's annoying requests for more packages as you click through its GUI; the downside is the time to download and install about 900 packages. Below ("Read more >>") is a link to a video of me running through the three lines above:

Oct 27, 2016

ChainLadder version 0.2.3 available on CRAN

ChainLadder is an R package for actuarial analysis of General / Property & Casualty insurance reserves. Version 0.2.3 on CRAN is is the first update in about a year. For the most part, the new version expands upon existing capabilities, as illustrated in the News vignette. Two of the most important are

  • the rownames (origin period) of a Triangle need no longer be numeric -- for example, accident years may be labeled with the beginning date of the period
  • the exposures of a glmReserve analysis may use names to match with origin period
Comments and contributors (!) are always welcome. Please refer to the package's repository.

Oct 16, 2016

October 2016 BARUG Meeting

The October meeting of the San Francisco Bay Area R User Group held at Santa Clara University consisted of socializing, an intro, and three speakers. In the intro, host representative Sanjiv Das highlighted the curriculum and advisory board of the school's new MS in Business Analytics program. The first speaker, yours truly, reenacted Sara Silverstein's Benford's Law post using R and insurance industry data (see previous posts in this blog). In light of the yahoo email scandal that broke that same day, it was posed to attendees whether a similar "law" might be found to discriminate between harmless and harmful emails without regard to message content. The last comment from the audience seemed to capture the evening's temperament: "Snooping is snooping!"

The other two timely talks dealt with election forecasting.

Mac Roach previewed a new online app from Alteryx to predict U.S. election results at the neighborhood level. Equally interesting was Mac's countrywide display, which was the first time I had seen graphical evidence of the increasing polarity of the American electorate, a disturbing trend IMO.

The last speaker, Pete Mohanty, spoke about presidential forecasting using bigKRLS. I was struck by the existence of a closed form solution to the problem. Pete's slides can be found here.

For a brief summary of the meeting, see BARUG's Meetup site.

Sep 8, 2016

Benford's Law in R (cont.): Actual Data

This is the second post based on Sara Silverstein's blog on Benford’s Law. Previously we duplicated the comparison of the proportion of first digits from a series of randomly generated numbers, and successive arithmetic operations on those numbers, and saw that the the more complicated the operation, the closer the conformance.

In this post we investigate the conformance with actual data, similar to Ms. Silverstein's investigation of "all the values from Apple's financials for every quarter over the past ten years."

Four different types of financial documents from property/casualty insurance were investigated:

1. An exhibit of estimated ultimate loss using various actuarial methods, and related calculated values
Exhibits.pdf
This exhibit includes financial values as well as some non-financial numbers, such as rows labeled with years, which could skew the results.

2. A Massachusetts insurance company rate filing 

In addition to many financial values, rate filings include much text and many numbers that are non-financial in nature.

3. An insurance company annual statement from 2009

Annual statements (aka, the Yellow Book) include many, many, many, many, many, many financial values.

4.  Schedule P data compiled by the Casualty Actuarial Society

Schedule P for six different lines of business for all U.S. property casualty insurers can be found at this link. The six files were combined into a single document. To isolate the investigation to purely financial numbers sans labels, company codes, and the like, the columns investigated are "IncurLoss_", "CumPaidLoss_", and "BulkLoss_".

Here are the results. The number of non-zero numbers in each document is indicated on the plot.


The Schedule P data is the most purely-financial in nature, and its plot in black matches Benford's Law almost exactly. Perhaps surprising, the Exhibits document is also quite close even though it holds the least number of observations. Perhaps a better job of pulling purely financial numbers out of the Rate Filing and the Annual Statement would improve their conformance.

Appendix


For reading PDF documents into R as text strings, I used the readPDF function in the tm package. Look at this link to learn how to download the binary files that make readPDF work easily, and the suggestion of where to store them for expediency.

To divide strings of characters into individual "words", I used 'scan' in base R. See this link.

For parsing numbers, in all their various forms with commas, decimal points, etc., I used the parse_number function in the readr package.

sessionInfo()


R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] readr_1.0.0 tm_0.6-2 NLP_0.1-9

loaded via a namespace (and not attached):
[1] assertthat_0.1 rsconnect_0.4.3 parallel_3.3.1 tools_3.3.1 tibble_1.2
[6] Rcpp_0.12.5 slam_0.1-38