Building package functions

Developing R Packages

Jasmin Ludolf

Content Developer

R package structure

Example package structure

Developing R Packages

Different temperature scales

  • What is 35 degrees Celsius (C) in Fahrenheit (F)?

Confused on the beach

Developing R Packages

Converting using R

 

C_value <- 35
F <- 9/5 * C_value + 32
F
[1] 95
Developing R Packages

Refresher on R functions

temp_converter <- function(

value, unit_from = "Celsius", unit_to = "Fahrenheit") {
if (unit_from == "Celsius" && unit_to == "Fahrenheit") { return(value * 9/5 + 32)
} else if (unit_from == "Fahrenheit" && unit_to == "Celsius") { return((value - 32) * 5/9)
} else if (unit_from == unit_to) { warning("unit_from and unit_to are the same, value returned.") return(value)
} else { stop("Invalid unit_from or unit_to. Only 'Celsius' and 'Fahrenheit' are accepted.") } }
Developing R Packages

Using temp_converter()

temp_converter(100)
[1] 212
temp_converter(95, unit_from = "Fahrenheit", unit_to = "Celsius")
[1] 35
Developing R Packages

Some R function best practices

  1. Choose descriptive names
  2. Handle all inputs gracefully
  3. Focus on one thing
Developing R Packages

Store a function in a file

dump("temp_converter", 
     file = "R/temp_converter.R")

Current unitConverter package structure

Developing R Packages

Install the package with devtools

devtools::install()
-  checking for file 'DESCRIPTION' ...
-  preparing 'unitConverter':
-  checking DESCRIPTION meta-information ...
  --install-tests 
* installing to library
* installing *source* package 'unitConverter' ...
** R
** data
** inst
** testing if installed package can be loaded from temporary location
** testing if installed package can be loaded from final location
* DONE (unitConverter)
Developing R Packages

Call temp_converter() temperature_data

value unit
36.26 Celsius
library(unitConverter)

unitConverter:::temp_converter(
value = temperature_data$value[1], unit_from = temperature_data$unit[1], unit_to = "Fahrenheit")
[1] 97.268
Developing R Packages

Let's practice!

Developing R Packages

Preparing Video For Download...