You are going to make an R package that you are going to save and store on Github.
Make a new Github repository, with the name you want for your package
Make sure it’s public
You could name it “testPackage” if you would like1
Clone this new repository to your computer.
1 For R package names, avoid using special characters like “-” and “_” and spaces.
I am going to assume in these instructions that you named the package “testPackage”, but obviously if you named it something else, just replace the name.
3 Setup Your Package
Open up your local “testPackage” folder
Install “devtools”
In the terminal, run usethis::create_package(".")
This will create the package files in the current folder.
Add a new R script called “myfunc.r” to the “R/” folder
Add the following code to that script:
testPackage/R/myfunc.r
#' My first function#'#' @param a A numerical vector.#' @param b Also a numerical vector.#'#' @return A numerical vector of a + b * a.#' @export#'#' @examples#' myfunc(3, 5)myfunc <-function(a, b) { result <- a * b + areturn(result)}
In the terminal, run devtools::document()
Add a license by running usethis::use_mit_license() in the terminal
Commit all the files, and push to Github
4 Install and Load Your Package
Now, we are going to see how we can use this package in other projetcs.
Switch to a VS Code window with the “assignment-6” repository open
Since you made your package public on your Github account, you can install it using renv.
Install your package, renv::install("yourGithubUsername/testPackage")
Check to see if the following code works:
library(testPackage)myfunc(3, 5)
Can you access the help file for your function?
Check to see if you can see “testPackage” in the “renv/” folder.
5 Assignment Tasks
5.1 New Functions
Estimating Beta
The task here is to write a new function to estimate \(\beta\) for a linear regression:
\[
y = \beta X + \epsilon
\]\[
\Rightarrow \hspace{1cm} \widehat{\beta} = [X^\prime X]^{-1} X^\prime Y
\]
Where \(y\) is a vector of \(n\) observations, \(X\) is a \(nxk\) matrix of \(k\) variables, and \(\beta\) is a vector of \(k\) variables.
Write a function estimate_beta()
takes as inputs “y” and “X”
returns “beta_hat”
Custom Theme
Write a function that retuns your favorite ggplot2 theme.
You’ll need to use usethis::use_package("ggplot2") to add ggplot2 as a dependency. You may possibly need to add other packages if you want to use one of their themes as a starting point.
You should make at least 3 adjustments to a default theme.
Write a function my_theme()
returns your ggplot2 theme
Document, Check, and Push
Make sure to document your new functions
Run devtools::check() and see if you get any errors or warnings, try to fix them.
Push your package to Github
5.2 Using Your New Functions
Now you will use the functions you have written.
In your assignment folder,
Re-install your “testPackage” and load it.
Check estimate_beta()
Add the following code to your project, and run it to check your estimate_beta() function.