# This script accompanies the Developing_R_Packages.pdf by providing the
# actually useful R commands without all of the descriptive text.
# Henry Glick, Nov. 1, 2019
# last updated Oct. 31, 2019
#### (1) **Prepare system-level tools**----
browseURL("https://cran.r-project.org/bin/windows/Rtools/")
# xcode-select --install
browseURL("https://developer.apple.com/xcode/download/")
#### (2) **Install R packages**----
# See what packages are associated with devtools
browseURL("https://cran.r-project.org/web/packages/devtools/index.html")
# Imports = installed when you install main package
# Suggests = = not installed when you install main package, but good to have
# Check to see which packages need to be installed and which need to be updated
# (which, for a single package, is technically the same thing as installation
packages <- c("knitr", "roxygen2", "devtools")
x <- sapply(packages, function(i){
if(i %in% rownames(installed.packages())==FALSE){
cat("Please install ", i, "\n")
} else if (any(grepl(pattern = i, old.packages()[,1])) == TRUE){
cat("Please update ", i, "\n")
}
})
# Install or update these three packages as required on your system
install.packages("devtools", dependencies = TRUE)
install.packages("knitr", dependencies = TRUE)
install.packages("roxygen2", dependencies = TRUE)
# or...
update.packages("devtools", dependencies = TRUE)
update.packages("knitr", dependencies = TRUE)
update.packages("roxygen2", dependencies = TRUE)
#----
# Load the requisite packages
require(devtools)
require(knitr)
require(roxygen2)
require(pkgbuild)
# Check your R search path to make sure everything is in order
search()
# Perform some checks to ensure your developer's toolset is in place
pkgbuild::has_rtools() #Is Rtools installed (Windows)?
pkgbuild::rtools_path() #Where is Rtools installed (Windows)?
pkgbuild::has_build_tools() #Are build tools available (Mac and Windows)?
print(pkgbuild::has_devel()) #Is a compiler available (Mac and Windows)?
pkgbuild::has_compiler() #Is a compiler available (Mac and Windows)?
print(pkgbuild::check_build_tools()) #Are build tools available (Windows)?
Sys.getenv('PATH') #Check your Windows System PATH variables
print(system('g++ -v')) #Maybe how you check this on a Mac, not sure...
# If Rtools does not show up on your PATH in Wondows, you need to add R to your
# PATH manually. Visit
# Start/computer/systems properties/advanced system settings/Environment variables
# in the lower box select path > Edit
#### (3) **Create package directory**----
setwd("C:\\Users\\ar2324\\Downloads\\10-25 First Steps with R\\Developing_R_Packages\\Directory")
usethis::create_package("statlab101")
#### (4) **Write R functions**----
#' A permutation test and plotting function
#'
#' This function performs a permutation test for the correlation of two samples
#' returning the p-value associated with your original Pearson's correlation,
#' relative to the null permutation distribution.
#'
#' Lots of descriptive details could go here. This line just holds the place.
#'
#' @param x One continuous variable
#' @param y Another continuous variable
#' @param n_samp The number of permutation iterations. Defaults to 10000
#' @param plot Return a histogram of the permutation distribution with your
#' sample correlation? Defaults to TRUE
#' @return This function returns either a graphical display of a permutation tes
#' of Pearson's correlation between x and y, when plot = T, or the probability
#' of obtaining the correlation between x and y.
#' @keywords methods htest
#' @export
#' @examples
#' x <- 1:100
#' y <- jitter(x, factor=100)
#' permCor(x, y, n_samp = 1000, plot = T)
permCor <- function(x, y, n_samp = 10000, plot = T){
corResults <- rep(NA, n_samp)
for (i in 1:n_samp){
corResults[i] <- cor(x, sample(y))
}
pval <- mean(abs(corResults) >= cor(x,y))
if (plot == T){
#Make histogram of permuted correlations
hist(corResults, col = "yellow", main = "", xlab = "Correlations", breaks = 50,
xlim = range(corResults,cor(x,y)))
mtext("Permuted Sample Correlations", cex = 1.2, line = 1)
mtext(paste("Permuted P-value =",round(pval,5)), cex = 1, line = 0)
abline(v = cor(x,y), col="blue", lwd=3)
text(cor(x,y)*1.01, 0,paste("Actual Correlation =", round(cor(x,y),2)),
srt = 90, adj = 0)
}
if (plot == F){
return(round(pval,5))
}
}
#### (5) **Adding processed data**----
# Read some data from the web, isolate variables, and rename
ugpts <- read.csv("http://reuningscherer.net/fes781/data/ugdata.csv")
ugpts <- ugpts[, 2:3]
colnames(ugpts) <- c("lon", "lat")
head(ugpts)
#Your working directory must be the package folder for the following function to
#work. Thus, we change directories from the parent of the package directory, to
#the package directory proper.
setwd("./statlab101")
usethis::use_data(ugpts, overwrite=TRUE)
#### (6) **Adding script files**----
# Programmatically create an installation directory and a sub-directory for scripts
dir.create(path = "inst")
dir.create(path = "inst/scripts")
# Now open a new file in RStudio, type anything you want, and save it as a .R
# file to the "inst/scripts" directory.
#### (7) **Adding other files**----
# Create a new directory
dir.create(path = "inst/images")
# Put something into that directory
download.file(url = "https://www.r-project.org/logo/Rlogo.png",
destfile = 'inst/images/Rlogo.png', mode = 'wb')
#### (8) **Modify the DESCRIPTION file**----
Imports:
rgdal,
proj4,
lastPackageName
Authors@R: person(given = "Henry", family = "Glick", role = c("aut", "cre"), email = "henry.glick@yale.edu")
#### (9) **Document and build**----
# Be sure working directory is the new package directory
devtools::document() # Use roxygen to document your package
setwd("../") #To build you need to be in the package's parent directory
devtools::build(pkg = "statlab101", path = getwd(), binary = FALSE) #Build tarball for installation on any platform
#### (10) **Install your package and test**----
# Be sure you specify the correct directory!
install.packages("./statlab101_0.0.0.9000.tar.gz", repos = NULL, type="source")
# Be sure you specify the correct directory!
devtools::install_local("./statlab101_0.0.0.9000.tar.gz", upgrade="ask", force=TRUE)
require(statlab101)
# Check to see that the package was properly loaded
isNamespaceLoaded("statlab101")
# Check the contents of your package
ls("package:statlab101")
# See what scripts are in your package (provided you made a "scripts" directory)
list.files(system.file(package="statlab101", "scripts"))
# Programmatically open a script from the package
file.edit(system.file(package="statlab101", "scripts/Script_01.R"))
# Want to open a script or RMarkdown file, or PDF, etc manually by browsing
# through folder structure? Great. Where are the files located?
system.file("scripts", package="statlab101")
# Check to see if your help file looks correct
?permCor
# See if your function actually works
permCor(x = 1:100, y = jitter(1:100, factor = 500), n_samp = 10000, plot = T)
#### (11) **Not satisified?**----
# Remove your package from the search() path (memory)
detach("package:statlab101", unload = TRUE)
# Delete your package from your library
remove.packages("statlab101", .libPaths())
#### (12) **Sharing packages**----
devtools::install_github("rajaoberison/test")
require(statlab101)
?permCor
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.