Basic skills in R: Installation, activation and use of R packages
Using something from a package without activating the whole package
Suppose you want to use a dataset from a given installed package without activating the complete package, say the Arthritis
dataset from the installed package vcd. Then you could do this via the following instruction:
> install.packages("vcd")
> df <- vcd::Arthritis > str(df) 'data.frame': 84 obs. of 5 variables: $ ID : int 57 46 77 17 36 23 75 39 33 55 ... $ Treatment: Factor w/ 2 levels "Placebo","Treated": 2 2 2 2 2 2 2 2 2 2 ... $ Sex : Factor w/ 2 levels "Female","Male": 2 2 2 2 2 2 2 2 2 2 ... $ Age : int 27 29 30 32 46 58 59 59 63 63 ... $ Improved : Ord.factor w/ 3 levels "None"<"Some"<..: 2 1 1 3 3 3 1 3 1 1 ... > head(df) ID Treatment Sex Age Improved 1 57 Treated Male 27 Some 2 46 Treated Male 29 None 3 77 Treated Male 30 None 4 17 Treated Male 32 Marked 5 36 Treated Male 46 Marked 6 23 Treated Male 58 Marked
In the first instruction, the double-colon operator ::
selects the named dataset from the so-called namespace of the installed package vcd
.
Similarly, you can refer to a specific function in the namespace of a particular installed package. This is handy when several activated package have a function with the same name and you want to use a particular one. As an example we import the function describe()
from the package Hmisc
.
> install.packages("Hmisc")
> data <- rnorm(100, mean = 3, sd = 2)
> imported_describe <- Hmisc::describe
> imported_describe(data) data n missing distinct Info Mean Gmd .05 .10 .25 .50 .75 .90 .95 100 0 100 1 3.199 2.563 -0.2415 0.3308 1.3713 3.0667 4.6743 6.4251 6.9968 lowest : -0.757107 -0.709402 -0.473129 -0.402703 -0.337565, highest: 7.04562 7.06119 7.10324 7.70968 8.44115
Unlock full access