Introduction

This chapter gives on overview of the book, but also introduces some fundamental concepts, such as objects, variables, and workspaces; saving and loading variables and objects; and R-scripts. Below is the supporting material for the sections of the chapter.

Variables and Objects

  • Script file: variables.R
  • Interactive notebook:

    In [1]:
    options(jupyter.rich_display=FALSE) # Create output as usual in R
    
    In [2]:
    # Defining two variables
    a <- 1
    b <- 2
    # Entering the name leads to printing the content of the variable
    a
    
    [1] 1
    In [3]:
    # Showing the variables defined:
    ls()
    
    [1] "a" "b"
    In [4]:
    # Removing variables:
    rm(a,b)
    # Checking the existence of a variable
    exists("a")
    
    [1] FALSE
    In [5]:
    # Defining and removing "hidden" variables
    a <- 1
    b <- 2
    x <- 3
    y <- 4
    z <- 42
    .zzyx <- 1412
    ls()
    
    [1] "a" "b" "x" "y" "z"
    In [6]:
    rm(list=ls())
    ls()
    
    character(0)
    In [7]:
    ls(all=TRUE)
    
    [1] ".pbd_env" ".zzyx"   
    In [ ]:
    
    

Saving and loading Objects

  • Script file: saving-and-loading-objects.R
  • Interactive notebook:

    In [5]:
    options(jupyter.rich_display=FALSE) # Create output as usual in R
    
    In [6]:
    # In this example we create the two variables 'a' and 'b':
    a <- 1
    b <- 1
    # We save them in the data file "ab.RData"
    save(a,b,file="ab.RData")
    # We then remove the two variables:
    rm(a,b)
    ls()
    
    character(0)
    In [7]:
    # With then load the data file
    load("ab.RData")
    # and verify that the two variables are restored
    ls()
    
    [1] "a" "b"
    In [8]:
    a
    
    [1] 1
    In [9]:
    b
    
    [1] 1

Working with R-scripts

  • Script file: running-scripts.R

    The code run in this script makes use of another script source-echo-demo.R which is (also available for download).

  • Interactive notebook:

    In [1]:
    ## Running a script with and without echo
    source("source-echo-demo.R")
    
    Hello world!
    [1] 1
    [1] 2
    
    In [2]:
    source("source-echo-demo.R",echo=TRUE)
    
    > cat("Hello world!\n")
    Hello world!
    
    > a <- 1
    
    > b <- 2
    
    > a
    [1] 1
    
    > print(a)
    [1] 1
    
    > b
    [1] 2
    
    > show(b)
    [1] 2