Essential Statistics with R and Quarto

Introduction: Demo

Author

Bongani Ncube

Instructor coordinates
  • Department of Mathematics and Computational Sciences , University of Zimbabwe
  • Business and Systems Analyst at @Optimum
  • Biostatistician and infectious disease modeler.

What is R?

  • R is an open source programming language and environment.
  • It is designed for data analysis, graphical display and data simulations.
  • It is one of the world’s leading statistical programming environments.

Why use R?

  • R is open-source! This means that it is free, and constantly being updated and improved.
  • It is compatible. R works on most existing operating systems.
  • R can help you create tables, produce graphs and do your statistics, all within the same program. So with R, there is no need to use more than one program to manage data for your publications. Everything can happen in one single program.
  • More and more scientists are using R every year. This means that its capacities are constantly growing and will continue to increase over time. This also means that there is a big online community of people that can help with any problems you have in R.

Question 1

Which of the following statements about R are True:

R is open-source

You need to pay a monthly fee to Posit inorder to use R

R is mainly used by software developers

R is used for game development and general Applications

Question 2

R Stands for React:

TRUE

FALSE

R as a One stop shop for data science workflows

Always saves my day!

very flexible

Amazing Community

all you need

Using RStudio

RStudio is an integrated development environment (IDE) for R. Basically, it’s a place where you can easily use the R language, visualize tables and figures and even run all your statistical analyses. We recommend using it instead of the traditional command line as it provides great visual aid and a number of useful tools that you will learn more about over the course of this workshop.

It includes a console, and a syntax-highlighting editor that supports direct code execution with tools for plotting, history, debugging and workspace management.

It integrates with R (and other programming languages) to provide a lot of useful features:

  • RStudio supports authoring HTML, PDF, Word, and presentation documents
  • RStudio supports version control with Git (direction to Github) and Subversion
  • RStudio makes it easy to start new or find existing projects
  • RStudio supports interactive graphics with Shiny and ggvis

There are other IDE for R: Atom, Visual Studio, Jupyter notebook, and Jupyter lab

Open RStudio

RStudio logo

The RStudio interface

When you open RStudio for the first time, the screen will be divided across three main Pane groups:

  1. Console, Terminal, Job group;
  2. Environment, History, Connections group;
  3. Files, Plot, Packages, Help, Viewer panes; and
  4. Script pane group

Once you Open a Script or Create a New Script (File > New File > R script or Ctrl/Cmd + Shift + N), the fourth panel will appear.

interface

pane 1

pane 2

cheatsheet

Writing an R script

An R script is a text file that contains all of the commands you will use. Once written and saved, your R script will allow you to make changes and re-run analyses with little effort.

Question 3

Which of the following statements about Rstudio is FALSE:

RStudio supports authoring HTML, PDF, Word, and presentation documents.

RStudio supports version control with Git (direction to Github) and Subversion.

RStudio makes it easy to start new or find existing projects

RStudio does not support interactive graphics with Shiny and ggvis

Commands & Comments
  • Use the ‘# symbol’ to denote comments in scripts.
  • The ‘# symbol’ tells R to ignore anything remaining on a given line of the script when running commands.
  • Since comments are ignored when running script, they allow you to leave yourself notes in your code or tell collaborators what you did.
  • A script with comments is a good step towards reproducible science, and annotating someone’s script is a good way to learn. Try to be as detailed as possible!
# This is a comment, not a command

Section Heading

You can use four # signs in a row to create section headings to help organize your script. This allows you to move quickly between sections and hide sections. For example:

#### Housekeeping ####

Housekeeping

  • The first command at the top of all scripts should be rm(list=ls()). This will clear R’s memory, and will help prevent errors such as using old data that has been left in your workspace.
A<-"Test" # Put some data in workspace
A <- "Test" # Add some spaces to organize your data!
A = "Test" # You can do this, but it does not mean you should
# Check objects in the workspace
ls()
# [1] "A"
A
# [1] "Test"
# Clean Workspace
rm(list=ls())
A

Important Reminders

  1. R is ready for commands when you see the chevron ‘>’ displayed in the terminal. If the chevron isn’t displayed, it means you typed an incomplete command and R is waiting for more input. Press ESC to exit and get R ready for a new command.
  2. R is case sensitive. i.e. “A” is a different object than “a”
a<-10
A<-5
a
A

rm(list=ls())  # Clears R workspace again

Question 4

Which of the following symbols is used for comments in R:

#

%--%

//

/*

Using R as a calculator

The first thing to know about the R console is that you can use it as a calculator.

Arithmetic Operators

  • Additions
1+1
_webr_editor_1 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  • Subtractions
10-1
_webr_editor_2 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  • Multiplications
2*2
_webr_editor_3 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  • Divisions
8/2
_webr_editor_4 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  • Exponents
2^3
_webr_editor_5 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.


Exercise 1

Use R to calculate the following skill testing question:

2+162456

_webr_editor_6 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.


Exercise 2

Use R to calculate the following skill testing equation:

2+162456/(2+1)457

Pay attention to the order of operations when thinking about this question!

Note that R always follows the order of priorities.

_webr_editor_7 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Manipulating objects in R

Objects

You have learned so far how to use R as a calculator to obtain various numerical values. However, it can get tiresome to always write the same code down in the R console, especially if you have to use some values repeatedly. This is where the concept of object becomes useful.

R is an object-oriented programming language. What this means is that we can allocate a name to values we’ve created to save them in our workspace. An object is composed of three parts:

  • a value we’re
  • an identifier and
  • the assignment operator.

  1. The value can be almost anything we want: a number, the result of a calculation, a string of characters, a data frame, a plot or a function.
  2. The identifier is the name you assign to the value. Whenever you want to refer to this value, you simply type the identifier in the R console and R will return its value. Identifiers can include only letters, numbers, periods and underscores, and should always begin with a letter.
  3. The assignment operator resembles an arrow (<-) and is used to link the value to the identifier.

The following code clarifies these ideas:

## Let's create an object called mean_x.
## The # symbol is used in R to indicate comments. It is not processed by R.
# It is important to add comments to code so that it can be understood and used by other people.
mean_x <- (2 + 6) / 2
# Typing its name will return its value.
mean_x
_webr_editor_8 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Here, (2 + 6) / 2 is the value you want to save as an object. The identifier mean_x is assigned to this value. Typing mean_x returns the value of the calculation (i.e. 4). You have to be careful when typing the identifier because R is case-sensitive: writing mean_x is not the same as writing MEAN_X. You can see that the assignment operator <- creates an explicit link between the value and the identifier. It always points from the value to the identifier. Note that it is also possible to use the equal sign = as the assignment operator

Good practices in R code

Name

  • Try having short and explicit names for your variables. Naming a variable var is not very informative.
  • Use an underscore (_), or a dot (.) to separate words within a name and try to be consistent!
  • Avoid using names of existing functions and variables (e.g., c, table, T, etc.)

Space

  1. Add spaces around all operators (=, +, -, <-, etc.) to make the code more readable.
  2. Always put a space after a comma, and never before (like in regular English).

Question 4

Which of the following symbols is an assigning operator in R:

#

<-

:=

==

Question 5

Which of the following is not a good practice when naming variables:

Use an underscore (_), or a dot (.) to separate words within a name and try to be consistent!

Use spaces to separate words within a name when you are under pressure

Try having short and explicit names for your variables

You can use names of existing functions and variables

Question 6

How do you create a variable named x with a numeric value of 5:

x<-5

x->5

int x=5

x:5

Question 6

Which one of the following is not an arithmetic sympol in R:

$

+

-

^

CHALLENGE 1

  • Create an object with a value of 1 + 1.718282 (Euler’s number) and name it euler_value

  • Create an object with the area of a circle that has radius of 26 cm

_webr_editor_9 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Data types and structure

Core data types in R

Data types define how the values are stored in R. We can obtain the type and mode of an object using the function typeof(). The core data types are:

  • Numeric-type with integer and double values
(x <- 1.1)
typeof(x)

(y <- 2L)
typeof(y)
_webr_editor_10 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  • Character-type (always between " ")
z <- "hie my name is Bongani Ncube!"
typeof(z)
_webr_editor_11 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  • Logical-type
t <- TRUE
typeof(t)

f<- FALSE
typeof(f)
_webr_editor_12 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Question 6

Which one of the following is not a data type:

Numeric

Character

logical

vector

Data structure in R: scalars

Until this moment, we have created objects that had just one element inside them. An object that has just a single value or unit like a number or a text string is called a scalar.

#Examples of scalars
a <- 100
b <- 3/100
c <- (a+b)/b
d <- "species"
e <- "genus"
_webr_editor_13 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

combinations of scalars

By creating combinations of scalars, we can create data with different structures in R.

Using R to analyze your data is an important aspect of this software. Data comes in different forms and can be grouped in distinct categories. Depending on the nature of the values enclosed inside your data or object, R classifies them accordingly. The following figure illustrates common objects found in R.

Data structure in R: vectors

  • A vector is an entity consisting of several scalars stored in a single object.
  • All values in a vector must be the same mode which are either numeric, character and logical.
  • Character vectors include text strings or a mix of text strings and other modes. You need to use "" to delimit elements in a character vector.
  • Logical vectors include TRUE/FALSE entries only. A vector with a single value (usually a constant) is called an atomic vector.
  • When you have more than one value in a vector, you need a way to tell R to group all these values to create a vector. The trick here is to use the c() function in this format: vector.name <- c(value1, value2, value3, ...).
  • The function c() means combine or concatenate. It is a quick and easy function so remember it!

examples in R

## Create a numeric vector with the c (which means combine or concatenate) function.
## We will learn about functions soon!
num_vector <- c(1, 4, 3, 98, 32, -76, -4)

## Create a character vector. Always use "" to delimit text strings!
char_vector <- c("blue", "red", "green")

## Create a logical or boolean vector. Don't use "" or R will consider this as text strings.
bool_vector <- c(TRUE, TRUE, FALSE)

##It is also possible to use abbreviations for logical vectors.
bool_vector2 <- c(T, T, F)
_webr_editor_14 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Question 8

How do you create a vector of all in the vowels?:

[a,b,c,d,e]

(a,b,c,d,e)

c(a,b,c,d,e)

{a,b,c,d,e}

Creating vectors of sequential values:

a:b

The a:b takes two numeric scalars a and b as arguments, and returns a vector of numbers from the starting point a to the ending point b, in steps of 1 unit:

(ncube1<-1:8)

(ncube2<-7.5:1.5)
_webr_editor_15 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

seq()

seq() allows us to create a sequence, like a:b, but also allows us to specify either the size of the steps (the by argument), or the total length of the sequence (the length.out argument):

seq(from = 1, to = 10, by = 2)

seq(from = 20, to = 2, by = -2)
_webr_editor_16 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

rep()

rep() allows you to repeat a scalar (or vector) a specified number of times, or to a desired length:

rep(x = 1:3, each = 2, times = 2)

rep(x = c(1,2), each = 3)
_webr_editor_17 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

CHALLENGE 2

  • Create a vector containing the first five odd numbers (starting from 1) and name it odd_n.
  • Create a vector containing any five cities you know in Zimbabwe
_webr_editor_18 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Operations using vectors

  • vectors can be used for calculations. The only difference is that when a vector has more than 1 element, the operation is applied on all elements of the vector. The following example clarifies this.
## Create two numeric vectors.
x <- c(1:5)
y <- 6

## Let's sum both vectors.
## 6 is added to all elements of the x vector.
x + y

## Let's multiply x by y
x * y
_webr_editor_19 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Lists

A list allows you to

  • gather a variety of objects under one name in an ordered way
  • these objects can be matrices, vectors, data frames, even other lists
  • a list is some kind super data type
  • you can store practically any piece of information in it!

example in R

my_list <- list(one = 1,
two = c(1, 2),
five = seq(1, 4, length=5),
six = c("Bongani", "Lenny"))
names(my_list)
_webr_editor_20 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

indexing lists

my_list[2]
my_list[[2]]
_webr_editor_21 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

matrices
  • While vectors have one dimension, matrices have two dimensions, determined by rows and columns.
  • like vectors and scalars matrices can contain only one type of data: numeric, character, or logical.

There are many ways to create your own matrix. Let us start with a simple one:

(mat1<-matrix(data = 1:10,
nrow = 2,
ncol = 5))
_webr_editor_22 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

(mat2<-matrix(c(1,2,3,4,5,6),
nrow = 2,
ncol = 3))
_webr_editor_23 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

(mat3<-matrix(c(1,2,3,4,5,6),2,3))

(mat4<-matrix(c(1,2,3,4,5,6),2,3,byrow = TRUE))
_webr_editor_24 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

We can also combine multiple vectors using cbind() and rbind():

nickname <- c("kat", "gab", "lo")
animal <- c("dog", "mouse", "cat")

(matrix5<-rbind(nickname, animal))

(matrix6<-cbind(nickname, animal))
_webr_editor_25 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

calculations with matrices

Similarly as in the case of vectors, operations with matrices work just fine:

(mat_1 <- matrix(data = 1:9,
nrow = 3,
ncol = 3))
(mat_2 <- matrix(data = 9:1,
nrow = 3,
ncol = 3))
_webr_editor_26 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

The product of the matrices is:

mat_1 * mat_2
_webr_editor_27 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Division of matrices

mat_1 %*% mat_2
_webr_editor_28 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

CHALLENGE 3

  1. Create an object containing a matrix with 2 rows and 3 columns, with values from 1 to 6, sorted per column.
  2. Create another object with a matrix with 2 rows and 3 columns, with the names of six animals you like.
_webr_editor_29 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

data frames
  • A data frame is a group of vectors of the same length (i.e. the same number of elements). Columns are always variables and rows are observations, cases, sites or replicates.
  • Differently than a matrix, a data frame can contain different modes saved in different columns (but always the same mode in a column).

It is in this format that ecological data are usually stored. The following example shows a fictitious dataset representing 4 sites where soil pH and the number of plant species were recorded. There is also a “fertilised” variable (fertilized or not). Let’s have a look at the creation of a data frame.

site_id soil_pH num_sp fertilised
A1.01 5.6 17 yes
A1.02 7.3 23 yes
B1.01 4.1 15 no
B1.02 6.0 7 no

example in R

# We first start by creating vectors.
site_id <- c("A1.01", "A1.02", "B1.01", "B1.02") #identifies the sampling site
soil_pH <- c(5.6, 7.3, 4.1, 6.0) #soil pH
num_sp <- c(17, 23, 15, 7) #number of species
fertilised <- c("yes", "yes", "no", "no") #identifies the treatment applied

# We then combine them to create a data frame with the data.frame function.
soil_fertilisation_data <- data.frame(site_id, soil_pH, num_sp, fertilised)

# Visualise it!
soil_fertilisation_data
_webr_editor_30 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Note how the data frame integrated the name of the objects as column names

Indexing

Indexing a vector

Typing an object’s name in R returns the complete object. But what if our object is a huge data frame with millions of entries? It can easily become confusing to identify specific elements of an object. R allows us to extract only part of an object. This is called indexing. We specify the position of values we want to extract from an object with brackets [ ]. The following code illustrates the concept of indexation with vectors.

Lets do it in R

  • Create a vector to use:
odd_n <- c(1, 3, 5, 7, 9)
_webr_editor_31 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  • To obtain the value in the second position, we do as follows:
odd_n[2]
_webr_editor_32 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  • We can also obtain values for multiple positions within a vector with c()
odd_n[c(2, 4)]
_webr_editor_33 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  • We can remove values pertaining to particular positions from a vector using the minus (-) sign before the position value
odd_n[c(-1, -2)]

odd_n[-4]
_webr_editor_34 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  • If you select a position that is not in the numeric vector
odd_n[c(1,6)]
_webr_editor_35 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

There is no sixth value in this vector so R returns a null value (i.e. NA). NA stands for ‘Not available’.

# You can use logical statement to select values.
odd_n[odd_n > 4]

# REMEMBER PREVIOUS VECTOR
char_vector
# Extract all elements of the character vector corresponding exactly to "blue".
char_vector[char_vector == "blue"]
# Note the use of the double equal sign ==.
_webr_editor_36 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.


CHALLENGE 4

num_vector <- c(1, 4, 3, 98, 32, -76, -4)
_webr_editor_37 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Using the vector num_vector and our indexing abilities:

  1. Extract the 4th value of the num_vector vector.
_webr_editor_38 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  1. Extract the 1st and 3rd values of the num_vector vector.
_webr_editor_39 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  1. Extract all values of the num_vector vector excluding the 2nd and 4th values.
_webr_editor_40 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

  1. Extract from the 6th to the 10th value.
_webr_editor_41 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Naming vectors

my_vector <- c("Bongani Ncube", "Data Analyst")
names(my_vector) <- c("Name", "Profession")
my_vector
_webr_editor_42 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Inspect my_vector using:

  • the attributes() function
  • the length() function
  • the str() function

Indexing a data frame

For data frames, the concept of indexation is similar, but we usually have to specify two dimensions: the row and column numbers. The R syntax is

dataframe[row number, column number].

Here are a few examples of data frame indexation. Note that the first four operations are also valid for indexing matrices.

# Extract the 1st row of the data frame
soil_fertilisation_data[1, ]

# Extract the 3rd columm
soil_fertilisation_data[, 3]

# Extract the 2nd element of the 4th column
soil_fertilisation_data[2, 4]

# Extract lines 2 to 4
soil_fertilisation_data[2:4]
_webr_editor_43 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

We can subset columns from it using the column names:

##Remember that our soil_fertilisation_data data frame had column names?
soil_fertilisation_data

##We can subset columns using column names:
soil_fertilisation_data[ , c("site_id", "soil_pH")]
_webr_editor_44 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

# And, also subset columns from it using "$"
soil_fertilisation_data$site_id
_webr_editor_45 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

A quick note on logical statements

R gives you the possibility to test logical statements, i.e. to evaluate whether a statement is true or false. You can compare objects with the following logical operators:

Operator Description
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== exactly equal to
!= not equal to
x | y x OR y
x & y x AND y

The following examples illustrate how to use these operators properly.

# First, let's create two vectors for comparison.
x2 <- c(1:5)
y2 <- c(1, 2, -7, 4, 5)

# Let's verify if the elements in x2 are greater or equal to 3.
# R returns a TRUE/FALSE value for each element (in order).
x2 >= 3

# Let's see if the elements of x2 are exactly equal to those of y2.
x2 == y2

# Is 3 not equal to 4? Of course!
3 != 4
_webr_editor_46 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

testing conditions

We can, for instance, test if values within a vector or a matrix are numeric:

char_vector
is.numeric(char_vector)

odd_n
is.numeric(odd_n)
_webr_editor_47 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Or whether they are of the character type:

char_vector
is.character(char_vector)

odd_n
is.character(odd_n)
_webr_editor_48 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

And, also, if they are vectors:

char_vector

is.vector(char_vector)
_webr_editor_49 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.


CHALLENGE 5

  1. Extract the num_sp column from soil_fertilisation_data and multiply its values by the first four values of the num_vector vector.
  2. After that, write a statement that checks if the values you obtained are greater than 25. Refer to challenge 9 to complete this challenge.

R packages

  • R packages extend the functionality of R by providing additional functions, and can be downloaded for free from the internet.

Install and load an R package

The ggplot2 package is a very popular package for data visualisation.

Install the package

install.packages("ggplot2")
_webr_editor_50 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Load the installed package

library(ggplot2)
_webr_editor_51 = Object {code: null, options: Object, indicator: Ke}
OJS Error

wf: Error in `mount(mountpoint, data_url)`: Can't download Emscripten filesystem image metadata.

Downloading package: knitr