We have uploaded an R package to github that hosts several functions accompanied by print methods functions. When we use devtools::install_github() to install the package and run one of the functions, its appropriate print function does not run. If the functions are imported directly into the Global Environment they work properly. To demonstrate, we have created a package called samplePackage
with a function called sampleFunction
which takes the mean of a given vector. The repository can be found on github at lj5yn/samplePackage.
See below the desired output when the sampleFunction
is correctly paired with a print method.
> x <- c(1,2,3,4,5)
> sampleFunction(x)
The mean of x is 3
The incorrect output we get is as follows:
> x <- c(1,2,3,4,5)
> sampleFunction(x)
$xMean
[1] 3
attr(,"class")
[1] "samplePackage_sampleFunction"
Below find two different specifications of the functions we have tried in github.
Try 1
#' Sample function
#'
#' Sample function that provides the mean.
#'
#' @param x The variable to use to compute the mean.
#'
#' @return The mean of x.
#'
#' @export
sampleFunction <- function(x) {
# x variable must be integer or numeric
if (!(typeof(x) %in% c("double", "integer", "numeric"))) {
stop("x variables must be type integer or numeric.", call. = FALSE)
return(NULL)
}
xMean <- sum(x)/length(x)
# Output Results
# Variable names added to dataset
resNames <- (list(
"xMean" = xMean))
class(resNames) <- "samplePackage_sampleFunction"
return(resNames)
}
print.samplePackage_sampleFunction <- function(x){
cat("The mean of x is ", x$xMean)
}
Try 2
Try 2 involves separating sampleFunction
and print.samplePackage_sampleFunction
into separate files. print.samplePackage_sampleFunction
goes into a file called prints and is grouped with the other R code function files in github.
#-------------------------------------------
## S3Methods print() // Updated 11.3.2021
#-------------------------------------------
#' S3Methods for Printing
#'
#' @name prints
#'
#' @aliases
#' print.samplePackage_sampleFunction
#'
#' @usage
#' \method{print}{sampleFunction}(x, ...)
#'
#' @description Prints for \code{samplePackage} objects
#'
#' @param x Object from \code{samplePackage} package
#'
#' @param ... Additional arguments
#'
#' @return Prints \code{samplePackage} object
#'
# Print sampleFunction
#' @export
print.samplePackage_sampleFunction <- function(x){
cat("The mean of x is ", x$xMean)
}
Based on Try2 method currently on lj5yn/samplePackage on github, please find the information contained in the NAMESPACE file below:
# Generated by roxygen2: do not edit by hand
S3method(print,samplePackage_sampleFunction)
export(sampleFunction)
We are hoping to get advice on how to properly specify the print function in github. Please let me know if any clarification or further information is needed.