The Console, Scripts, Help & Packages

[1] is the index of the first element shown on that line.

3.1 The console

[1] is the index of the first element shown on that line.

> 1 + 2
[1] 3
> x <- c(10, 20, 30)
> x
[1] 10 20 30
> q()          # quit (asks to save workspace — answer "n"; disable saving in RStudio options)

3.2 Scripts

Save code in .R files. In RStudio: Ctrl+Enter runs the current line/selection; Ctrl+Shift+S sources the file; Ctrl+Shift+M inserts the pipe.

source("analysis.R")        # run a script from the console

3.3 Comments

# Single-line comment (the only comment syntax)
#' roxygen2 documentation comment (used in packages)

3.4 Getting help

?mean                 # help page for mean
help("mean")
??regression          # search help across installed packages
help.search("linear model")
example(mean)         # run examples
args(mean)            # function arguments
vignette()            # list long-form guides
vignette("dplyr")
apropos("mean")       # functions whose name contains "mean"
RSiteSearch("mixed models")

3.5 Packages

library() attaches a package to the search path; :: accesses a function directly (good for scripts/packages to avoid name conflicts).

install.packages("tidyverse")                # from CRAN
install.packages(c("data.table", "ggplot2"))
library(ggplot2)                             # load (attach) a package
require(ggplot2)                             # returns FALSE instead of error (use in conditionals)
ggplot2::ggplot                              # use without attaching
update.packages()
remove.packages("pkg")
installed.packages()[, "Package"]
packageVersion("dplyr")
sessionInfo()                                # R version, OS, loaded packages

# From GitHub / other sources
install.packages("pak"); pak::pak("tidyverse/dplyr")
remotes::install_github("user/repo")
BiocManager::install("DESeq2")               # Bioconductor
install.packages("pkg", repos = "https://ropensci.r-universe.dev")

3.6 Workspace & working directory

Best practice: use RStudio Projects (.Rproj) and the here package (here::here("data", "file.csv")) so paths are relative to the project.

getwd()                       # current working directory
setwd("~/projects/analysis")  # change it (avoid in scripts — use projects instead)
ls()                          # objects in the global environment
rm(x); rm(list = ls())        # remove objects
save.image("work.RData")      # save all objects (generally discouraged)

3.7 Hello World

print("Hello, World!")
cat("Hello, World!\n")
message("Hello to stderr")