In answer to a question from a student:
I only need to include library(package) and not install.packages("package") in the coursework?
Yes, it's fine to just include library(package) in the .qmd file in the submission. I recommend putting #| include: false at the top if the code chunk that loads the packages as it's not the most interesting bit of code and to save space, you can mention which packages you used in the main text of the coursework.
Regarding the whether or not to include code to install packages, there are pros and cons:
- Pros: makes the code more reproducible: if the .qmd file installs necessary packages it will make it easier for others to run
- Cons: makes the code a bit more longer and complicated
I think the pros outweigh the cons. You can use code the following approach to detect which packages are currently installed and only install those that are not:
|
```{r} |
|
#| label: install-packages2 |
|
#| include: false |
|
# Note: this is just to demonstrate an alternative way of installing packages |
|
# that are not currently installed (only works with packages that are on CRAN) |
|
pkgs = c("tidyverse", "stats19", "sf") |
|
installed_pkgs = installed.packages() |
|
if (!all(pkgs %in% installed_pkgs)) { |
|
install.packages(pkgs[!pkgs %in% installed_pkgs]) |
|
} |
|
``` |
A fancier approach is to use the pak package to install the packages (not the line that installs pak if not installed), this approach can install GitHub packages also:
|
```{r} |
|
#| label: install-packages |
|
#| include: false |
|
pkgs = c("tidyverse", "stats19", "sf", "nptscot/osmactive") |
|
# Install pak pkg if not already installed |
|
if (!requireNamespace("pak", quietly = TRUE)) { |
|
install.packages("pak") |
|
} |
|
pak::pkg_install(pkgs) |
|
``` |
In answer to a question from a student:
Yes, it's fine to just include
library(package)in the .qmd file in the submission. I recommend putting#| include: falseat the top if the code chunk that loads the packages as it's not the most interesting bit of code and to save space, you can mention which packages you used in the main text of the coursework.Regarding the whether or not to include code to install packages, there are pros and cons:
I think the pros outweigh the cons. You can use code the following approach to detect which packages are currently installed and only install those that are not:
tds/d2/template.qmd
Lines 105 to 115 in 5119e12
A fancier approach is to use the
pakpackage to install the packages (not the line that installs pak if not installed), this approach can install GitHub packages also:tds/d2/template.qmd
Lines 94 to 103 in 5119e12