-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpackages.Rmd
77 lines (55 loc) · 2.36 KB
/
packages.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
---
title: 'Loading packages (Teaching an old dog new tricks)'
---
```{r, include=FALSE}
library(tidyverse)
```
## Packages {- #packages}
R has been around for ages. It remains popular because it's _easy for people to
add to it_.
You can run almost any statistical model and produce many different plots in R
because users write 'packages' which extend the base language. For now we assume
someone has helped you install all the packages you need^[See the
[installation guide](installation.html) if this isn't the case].
To _access_ features in packages, you normally load the package with the
`library()` function. Running `library(<packagename>)` loads all the new
functions within it, and it is then possible to call them from your code. For
example, typing:
```{r}
library(ggplot2)
```
Will load the `ggplot2` package. You can then call the `qplot` function it
provides:
```{r}
qplot(mtcars$mpg, bins=7)
```
:::{.tip}
It's good style to load packages at the top of an R script, or in the first
chunk of an RMarkdown document. This makes it easy for others to see what
packages they need to install, and helps avoid certain sorts of errors in your
code.
:::
#### {- #package-namespacing}
You don't strictly _need_ to load packages to use their features. If a package
is installed on your system you can also call a function it provides directly.
In the example below we call the `hist.data.frame` from the `Hmisc` package, and
obtain histograms of all the variables in the `mtcars` dataset:
```{r}
Hmisc::hist.data.frame(mtcars)
```
The rule is to type `package::function(parameters)`, where `::` separates the
package and function names. Parameters are just the inputs to the function.
There are two reasons not to load a package before using it:
1. Laziness: it can save typing if you just want to use one function from a
package, and only once.
2. Explicitness: It's an unfortunate truth that some function names are repeated
in different packages. This can be confusing if they work differently or do
comepletely different things. If you don't know which package the version you
are using comes from. Using `package_name:function_name` can help make things
explicit.
:::{.exercise}
Try using the `hist.data.frame` function in the `Hmisc` package on the `mtcars`
data.
- First using the `::` syntax
- Then load the `Hmisc` package, and repeat without using the `::`.
:::