In this lab, we will learn how to write an R package.
Goal: by the end of this lab, you should be able to write an R package.
Note that loading devtools also attaches
usethis.
library(devtools)create_tidy_package("FILEPATH/testing") to start a
new R package called testing.FILEPATH should be where you have all your SDS270
RStudio Project folders. Don’t nest this inside another RStudio Project
folder. For example
~/Documents/SDS270, then run
create_tidy_package("~/Documents/SDS270/testing")create_tidy_package("") in the console, put your
cursor in between the "", press TAB, find the directory you
have your SDS270 materials in, and then add /testingFILEPATH/testing/tests/ folderWithin the new "FILEPATH/testing" folder you just
created, delete the tests/ subfolder. This is used for unit
testing, which is a more advanced topic
DESCRIPTION fileTitle of your packageAuthors@R: Edit your last name, first name, and
emailroxygen2Go to “Tools -> Project Options… -> Build Tools” and make sure that:
Create a new .R R Script file and save it in the
R/ folder as functions.R. The R/
folder is where all R functions need to be saved.
add_two_numbers <- function(x, y){
z <- x + y
return(z)
}roxygen2add_two_numbers()
function, but not the lines that have { or
}add_two_numbers(4, 5)?add_two_numbersGo to your add_two_numbers() function and add:
x and ySee example on the screen
Added after lecture:
#' Add two numbers
#'
#' This is a braindead function to learn R packages with!
#'
#' @param x number 1
#' @param y number 2
#'
#' @return The sum of x and y
#' @export
#'
#' @examples
#' add_two_numbers(76, 66)
add_two_numbers <- function(x, y){
z <- x + y
return(z)
}add_two_numbers(4, 5)?add_two_numbersR CMD check by clicking on the “Check” button
under the “Build” tab.DESCRIPTION.
Rebuild the package.Under Imports, add each package you want your package to
use on a new line, separated by comma’s. Your package should never load
a package using library() or require(), rather
add it to the DESCRIPTION file.
Imports:
dplyr,
ggplot2ggplot()In your functions.R file, add:
#' Test Graph
#'
#' Tests whether I can use ggplot2
#'
#' @return graph
#' @export
#' @import ggplot2
#' @examples
test_graph <- function() {
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_point()
}@import line where we import the
ggplot2 packagetest_graph()Prompt: Paste the errors, warnings, or messages that you get from
R CMD checkto the#questionschannel. What questions do you have about what those mean?