Chapter 5 Basic R
Get help
- CRAN: https://cran.r-project.org
- Rdocumentation powered by datacamp, it has interactive interface with good examples, the typesetting also looks better, https://www.rdocumentation.org
- Posit Cheatsheets: https://posit.co/resources/cheatsheets/
R is case-sensitive; comments start with #.
Curly brackets or braces {} are used to keep code that needs to be run together as a single expression. This is commonly done when writing a function or when writing an if statement.
Double curly braces {{}} are used programming with tidyverse. See the dplyrprogramming vignette for details.
?Syntax to check precedence of operators.
Save & Load R objects
save(..., f_name) and saveRDS()
save() When loaded the named object is restored to the current environment (in general use this is the global environment — the workspace) with the same name it had when saved.
save writes an external representation of R objects to the specified file. The objects can be read back from the file at a later date by using the function load or attach (or data in some cases).
save(..., list = character(), file = stop("'file' must be specified"), ascii = FALSE, version = NULL, envir = parent.frame(), compress = isTRUE(!ascii), compression_level, eval.promises = TRUE, precheck = TRUE)
...The names of the objects to be saved (as symbols or character strings).listA character vector containing the names of objects to be saved.- The names of the objects specified either as symbols (or character strings) in
...or as a character vector inlistare used to look up the objects from environmentenvir.
- The names of the objects specified either as symbols (or character strings) in
filethe name of the file where the data will be saved.
saveRDS() doesn’t save the both the object and its name it just saves a representation of the object. As a result, the saved object can be loaded into a named object within R that is different from the name it had when originally serialized.
Serialization is the process of converting a data structure or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and “resurrected” later in the same or another computer environment.
saveRDS works only for saving a single R object, save() can save multiple R objects in one file. A workaround for saveRDS is to save all target objects in a single R object (e.g., in a list), and then use saveRDS() to save it at once.
datalist = list(mtcars = mtcars, pressure=pressure)
saveRDS(datalist, "twodatasets.RDS")
rm(list = ls())
datalist = readRDS("twodatasets.RDS")
datalistrm(list = ls()) removes all objects in the current environment. It will not unload the packages that you have loaded.
If you want to both remove all objects and unload all packages, you can restart your R session.
Load R objects
load(f_name) to load .rda file.
readRDS(f_name) to load .rds file.
Naming conventions:
rdaandrdsfor selected objects.RDatafor all objectes in your workspace- The file extensions are up to you; you can use whatever file extensions you want.
An example
> require(mgcv)
Loading required package: mgcv
This is mgcv 1.7-13. For overview type 'help("mgcv-package")'.
> mod <- gam(Ozone ~ s(Wind), data = airquality, method = "REML")
> mod
Family: gaussian
Link function: identity
Formula:
Ozone ~ s(Wind)
Estimated degrees of freedom:
3.529 total = 4.529002
REML score: 529.4881
> save(mod, file = "mymodel.rda")
> ls()
[1] "mod"
> load(file = "mymodel.rda")
> ls()
[1] "mod"
> ls()
[1] "mod"
> saveRDS(mod, "mymodel.rds")
> mod2 <- readRDS("mymodel.rds")
> ls()
[1] "mod" "mod2"
> identical(mod, mod2, ignore.environment = TRUE)
[1] TRUESave figures in a list
p_list <- list(p_ano=p_ano, p_tr=p_tr)
# p_list[[name]] <- p_obj
p_list[[1]]
f_name <- paste0(fig_dir, sprintf("trend_analysis/image_list_%s.rds", con_name))
# saveRDS(p_list, f_name)
# plot in a panel grid
p_allCON <- plot_grid(plotlist=p_list, align="vh", labels=sprintf("(%s)", letters[1:length(p_list)]), hjust=-1, nrow=3, label_size=12)
p_allCON