flat_template.Rmd for working package

library(testthat)
# Load already included functions if relevant
pkgload::load_all(export_all = FALSE)

Include some data examples in your package

# Run all this chunk in the console directly
# There already is a dataset in the "inst/" directory
# Make the dataset file available to the current Rmd during development
pkgload::load_all(path = here::here(), export_all = FALSE)

# You will be able to read your example data file in each of your function examples and tests as follows - see chunks below
datafile <- system.file("nyc_squirrels_sample.csv", package = "<my_package_name>")
nyc_squirrels <- read.csv(datafile, encoding = "UTF-8")

nyc_squirrels

The first function of the package: Calculate the median of a vector

#' My median
#'
#' @param x Vector of Numeric values
#' @inheritParams stats::median
#'
#' @return
#' Median of vector x
#' @export
#'
#' @examples
my_median <- function(x, na.rm = TRUE) {
  if (!is.numeric(x)) {stop("x should be numeric")}
  stats::median(x, na.rm = na.rm)
}
my_median(1:12)

# Example with your dataset in "inst/"
datafile <- system.file("nyc_squirrels_sample.csv", package = "<my_package_name>")
nyc_squirrels <- read.csv(datafile, encoding = "UTF-8")
# Apply my function
my_median(nyc_squirrels[,"hectare_squirrel_number"])
test_that("my_median works properly and show error if needed", {
  expect_true(my_median(1:12) == 6.5)
  expect_error(my_median("text"))
})

# Test with your dataset in "inst/"
datafile <- system.file("nyc_squirrels_sample.csv", package = "<my_package_name>")
nyc_squirrels <- read.csv(datafile, encoding = "UTF-8")
# Apply test on my function
test_that("my_median works properly with internal dataset", {
  expect_equal(my_median(nyc_squirrels[,"hectare_squirrel_number"]), 3)
})

Calculate the mean of a vector

Use sub-functions in the same chunk

#' My Other median
#'
#' @param x Vector of Numeric values
#' @inheritParams stats::median
#'
#' @return
#' Median of vector x
#' @export
#'
#' @examples
my_other_median <- function(x, na.rm = TRUE) {
  if (!is.numeric(x)) {stop("x should be numeric")}
  sub_median(x, na.rm =na.rm)
}

#' Core of the median not exported
#' @param x Vector of Numeric values
#' @inheritParams stats::median
sub_median <- function(x, na.rm = TRUE) {
  stats::median(x, na.rm)
}
my_other_median(1:12)
test_that("my_median works properly and show error if needed", {
  expect_true(my_other_median(1:12) == 6.5)
  expect_error(my_other_median("text"))
})
# Keep eval=FALSE to avoid infinite loop in case you hit the knit button
# Execute in the console directly
fusen::inflate(flat_file = "dev/flat_template.Rmd", vignette_name = "Get started")

Inflate your package

You're one inflate from paper to box. Build your package from this very Rmd using fusen::inflate()



Try the fusen package in your browser

Any scripts or data that you put into this service are public.

fusen documentation built on Aug. 17, 2023, 5:09 p.m.