Import Statements
library()
to Load a Package
Use library()
to load an installed package.
require()
as an Alternative
require()
works similarly to library()
but returns a logical value.
Aliasing with ::
Use package::function
to access a function without loading the entire package.
You can also chain it in pipe workflows:
Loading All Functions with attach()
This is not commonly recommended, but attach()
makes all variables from a dataset or list directly accessible.
Avoid attach()
in production—it can cause name conflicts and unexpected behavior.
Importing Custom Scripts
Use source()
to run R code from another file.
Suppose you have a file myutils.R
with the following content:
|_ myutils.R <- here
# myutils.R
<- function() {
greet print("Hello from myutils!")
}
Then in your main script:
|- myutils.R
|_ analysis.R <- here
# myutils.R
source("myutils.R")
greet()
[1] "Hello from myutils!"
Common Errors
Some frequent errors encountered when dealing with import statements in R.