Skip to Tutorial Content

Introduction

Welcome to your first Data Analytics tutorial.

This will be an adventure that will take you from a data-jungle to the radiant sky of knowledge. Don’t worry you won’t be bitten by pythons (none will be here) but lots of will get you to your destination.

We will begin our journey with a “hello world” scream and wrestle with math. Our first data-jungle encounter will show us the atomic types of . Then we will meet our new best friend data.frame.

Hello World & Arithmetics

It is custom to begin with a “Hello World” example. In the console window write:

cat('Hello World\n')

and then press Run Code and once you are happy with the result press Submit Answer, otherwise try the other two buttons.

cat('Hello World\n')

This prints the text Hello World. Here, we used the function cat which concatenates and prints. The string 'Hello World\n' could have be split into three parts.

cat('Hello','World','\n')

By the way \n means new line and ensures the command prompt will not be next to the string. Strings are identified by single or double quotes.

'Hello'
"World"

The console executes commands immediately. Try fundamental arithmetics \(1+2,~2-1,~3 \times 4, \frac{9}{3}\)

1+2; 2-1; 3*4; 9/3

You can concatenate and display the above with cat.

cat(1+2, 2-1, 3*4, 9/3)

Let’s try powers such as: \(2^4,~3^{-1},\sqrt{16}\)

cat(2^4, 3^-1, sqrt(16),16^(1/2))

Practice makes perfect

Display the sum of the numbers one to five divided by five.

# There are numerous ways to do this task.
# You may want to start with the display function
cat(...)
# Do not forget to close the brackets before dividing
cat((1 + 2 + 3 + 4 +5) ... )
cat((1+2+3+4+5)/5)

The average (aka. sample mean) is computed in this way, i.e.  \[\bar{x} = \frac{1}{n}\sum_{i=1}^n x_i = \frac{x_1+x_2+\dots+x_n}{n}\]

Display the text: “The golden ratio is:” and concatenate it with the calculation \(\frac{1+\sqrt{5}}{2}\). By the way, the background to the golden ratio is intruiging.

cat("The golden ratio is: ", (1+sqrt(5))/2)

Scalars, Vectors and Matrices

Scalars

In the previous exercises scalars were used. Now we will use them via variable names.

a = 1; b = 2; # this is a comment: declaration
c = a + b     # addition
c             # show result   

Let us analyse the above code. The first line assigns values to the variables \(a\) and \(b\). The first command is to assign the value 1 to a via a=1. In R it is very common to use <- as assignment operator. Try it - replace all = with <- in the above code. You can even assign variables from right to left, e.g. a+b -> c, which “feels” really strange if you have used other programming languages. The second command is b=2. Commands in the same line are seperated by a semicolon ;. We have added a comment at the end of line 1. Comments are identified with a hashtag #, and they are not computed.

Vectors

Definition and Access

Vectors are formed by concatenating scalars using the c() function.

x = c(1,2,3) # easiest way
# or using the previous variables 
a = 1; b = 2; c = a + b;
x = c(a,b,c)

The vector \(x = \left[\begin{array}{c} 1 \\2 \\ 3 \end{array}\right]\) has three elements. This can be confirmed using the function length. Each element can be obtained via its index using square-brackets.

x = c(1,2,3) 
cat('length = ', length(x), '\n')
cat('x1 = ', x[1], ', x2 = ', x[2], 'etc.')

Note that the first element has index 1 unlike in other programming languages.

Vectors are commonly known as arrays. Mathematicians prefer the term vector. Computer Scientists like the term array. In machine learning we will often call them feature. In statistical learning the term variable will come up.

Accessing several elements in vectors can be achieved using index vectors. For example, let us access the 2,3,2 and 5 element in the vector \(x = \begin{bmatrix}11&22&33&44&55\end{bmatrix}\) simultaneously.

x <- c(11,22,33,44,55) 
I <- c(2,3,2,5)  # index vector
x[I]

Addition and Transpose

Let \(x = \left[\begin{array}{c} 1 \\2 \\ 3 \end{array}\right]\) and \(y = \left[\begin{array}{c} 4 \\ 5 \\ 6 \end{array}\right]\) be vectors and \(x+y\) their sum.

x = c(1,2,3) 
y = c(4,5,6)
x + y

Although the above result looks like a row vector it is not. The transpose of it makes it clear. Generally, the transpose means that a row becomes a column vector or vice versa.

x = c(1,2,3) 
t(x)
t(t(x))

That means, by default they are already column vectors. The transpose function returns the array as a matrix.

Multiplication

There are several ways to multiply the vectors \(x\) and \(y\). We will look at the element-by-element multiplication and the scalar product.

The first one is also known as Hadamard product \(x \odot y\). For a vector with three elements we obtain: \(x\odot y = \begin{bmatrix}x_1 y_1 & x_2y_2 &x_3y_3\end{bmatrix}\). For instance,

x = c(1,2,3) 
y = c(4,5,6)
x * y

The scalar product \(x \cdot y\) also known as dot product (or matrix multiplication - we will come to this in a jiffy) is computed via
\(x\cdot y = x_1 y_1+x_2y_2+\dots +x_ny_n\) In R this is achieved with %*%.

x = c(1,2,3) 
y = c(4,5,6)
x %*% y

The above results pushed us to the frontier of the “world” of matrices, because a vector is “just” a one dimensional matrix.

Practice makes perfect

Create a vector \(y\) with elements one to ten using the colon operator :, then add the second and ninth element. Try to break up your solution approach in little chunks. First write 1:10 and press Run Code, then assign it to \(y\). At last calculate \(y_2+y_9\) (see hints).

y = 1:10
y[2]+y[9]

Assume you have two vectors \(u = \begin{bmatrix}5&2\end{bmatrix}^\intercal\) and \(v = \begin{bmatrix}2&4\end{bmatrix}^\intercal\).

Vector addition.

Vector addition.

What is \(u+v\)?

u = c(5,2); v=c(2,4)
u = c(5,2); v=c(2,4)
u+v

How can you double the size of vector \(\begin{bmatrix}7&6\end{bmatrix}\)?

# Use scalar multiplication, or add the same vector twice
2*c(7,6)

Assume \(u=\begin{bmatrix}1&2&3\end{bmatrix}\) and \(v=\begin{bmatrix}2&1&\frac{1}{3}\end{bmatrix}\). What is the Hadamard product \(u\odot v\)?

u = c(1,2,3); v=c(2,1,1/3)
u = c(1,2,3); v=c(2,1,1/3)
u*v

Given are \(u=\begin{bmatrix}1&2&3\end{bmatrix}\) and \(e=\begin{bmatrix}1&1&1\end{bmatrix}\). What is the dot product \(u\cdot e\)?

u = c(1,2,3); e=c(1,1,1)
u = c(1,2,3); e=c(1,1,1)
u%*%e

Beautiful side effect - the dot product of a vector \(u\) with a one-vector \(e\) is just the sum of the vector elements, i.e. \(u \cdot e = \sum_{i=1}^n u_i\)

Matrices

A matrix \(A = \left[\begin{array}{c} 1 & 4 \\2 & 5 \\ 3 & 6 \end{array}\right]\) can be created from vectors using the row or column bind functions:
x = c(1,2,3); y = c(4,5,6)
A = cbind(x,y) # column bind
B = rbind(x,y) # row bind
A;B

Another way to create \(A\) is by using the matrix function with the input ncol = 2.

A = matrix(c(1,2,3, 4,5,6), ncol = 2)

Now it is interesting to access individual elements of the matrix. For instance, assume you want to return the element located in row 3 and column 2.

A[3,2]

Let’s expand the matrix to make it more interesting.

B = cbind(A,A)
B
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    1    4
## [2,]    2    5    2    5
## [3,]    3    6    3    6

Let’s return the second row and third column.

B[2,]
## [1] 2 5 2 5
B[,3]
## [1] 1 2 3

Let’s return the second and fourth column of \(B\).

B[,c(2,4)]

Basic Datatypes

In this section we will look at classic R datatypes. We have looked at vectors, which is the most fundamental type in R. Previously, we had the example x=c(1,2,3). There are six basic data types: logical (binary number), integer (natural number), double (real number), complex, character (string) and raw (bytes), which are all in the form of vectors. The function typeof() will return these datatypes.

By default a numeric vector has a double data type.

x = c(1,2,3)
typeof(x)

In order to get an integer vector we need to add an L (long integer) to the numeric value.

x = c(1L,2L,3L)
typeof(x)
## [1] "integer"

Next we will look at the data types logical and character.

b = c(TRUE,FALSE,TRUE)
s = c('one','two','three')
cat('type of b:', typeof(b), ', length of b:', length(b))
cat('type of s:', typeof(s), ', length of s:', length(s))

The last output is interesting, because it returns length of the vectors. The vector \(s\) contains three string elements. Usually (e.g. Java), a string consists of characters. So, actually the data type character should be called string.

The questions arises how can we get characters out of a string. The function we need is substr(). Let’s extract the first two characters and characters 6 to 8.

s = 'Data Analytics'
cat( substr(s,1,2), substr(s,6,8))

By the way, nchar() returns the number of characters in a string.

There are two more basic datatypes complex and raw. The first one allows us to use complex numbers.

  u = 1+1i
  v = 1+0i
  cat( u + v, u - v, u*v, u/v)

The second one deals with byte operations. Let’s begin with a few numbers translated into bytes.

as.raw(c(0,2,8,9,10,15,32,64,128,255))

Note, the hexadecimal representation of the bytes. The bit representation can be achieved with:

rawToBits(as.raw(7))
## [1] 01 01 01 00 00 00 00 00

Practice makes perfect

Determine the type of 123.45:

typeof(123.45)

Extract the first character of str.

str = 'Data Analytics'
str = 'Data Analytics'
substr(str,1,1)

Extract the last two characters of str using nchar().

str = 'Data Analytics'
str = 'Data Analytics'
substr(str,nchar(str)-1,nchar(str))

Data-frames and Lists

Data-frames

Probably the most important data structure is the data.frame. In the previous section we created several vectors with different basic data types. Now we can put them together in a data.frame.

x = c(1,2,3)
b = c(TRUE,FALSE,TRUE)
s = c('one','two','three')
c = c(1+0i,1+1i,-1+0i)
D = data.frame(x,b,s,c)
D

This is similar to a matrix. However, a matrix only contains elements of one type. We observe that each column vector must have the same length.

cat(length(x),length(b),length(s),length(c))

Accessing elements can be achieved in the same way as in matrices. For instance let us extract the element in the second raw and third column.

D[2,3]

Similarly to matrices rows and columns can be extracted, e.g. second raw and third column.

D[2,]; D[,3]

Tip: Shall I use a matrix or a data-frame? If you can, always use the “simpler” structure. When all elements have the same datatype a matrix is simpler than a data-frame. By the way, also use a vector instead of a one-dimensional matrix.

Let us have a look at another example. Assume you have got several customers and information about them: create the following data frame.

customer <- c('Wolfgang','Eleanor','Vikas','Patrick')
salary   <- c(100,90,120,60)
years    <- c(10,3,8,1)
df <- data.frame(customer,salary,years)
df

This data frame has four rows aka. observations and three columns aka. variables or features.

A feature can be extracted from a data frame using the access operator $. Let us extract all customers from the data frame.

df$customer

An observation can be obtained using square-brackets:

df[2,]

Lists

Lists are a sequence of elements. For instance,

L = list(a_number=1, words=c('one','two'), binvec = c(TRUE,FALSE,TRUE))

Elements in a list are accessed differently to data-frames using [[]]. For instance,let us get the second element in the list, which is vector s.

L[[2]]

In a certain way a data.frame is a special list, where all elements are vectors with the same length.

It is possible to access column vectors in lists and data-frames by their name, using the list subset operator $. The function names() returns the names as expected.

names(L)

For instance, let us return x in D using $.

D$x

Practice makes perfect

Determine the number of rows (use nrow()).

cars = mtcars
nrow(cars)

Determine the number of columns (use ncol()).

cars = mtcars
cars

List all column names of mtcars.

You can find out more about R datasets using ? or help(). The datasets can be listed using: library(help = "datasets").

library(help = "datasets")
# help(mtcars) # get more information (opens in new window)

Determine the average number of miles per gallons.

# start with
mtcars$mpg
# for the average use
# mean(...)

Now, let’s get to the extreme level. List all car that are above the average mpg value. Your “cooking ingredients” are: rownames for the cars, mean for the average, the logical comparison > and logical indices [TRUE, FALSE, ...].

# start with the previous challenge
mean(mtcars$mpg)
# figure out each mpg
mtcars$mpg > mean(mtcars$mpg)
# try 
rownames(mtcars)
# put it all together using logical indizes
rownames(mtcars)[mtcars$mpg > mean(mtcars$mpg)]

Classes and Objects

This is advanced material. You can skip this section. It would help if you do the Controls & Function tutorial first.

Previously we heard about lists. A list can be converted into an object (more specifically into an S3 object). The class represents the common structure, an instance or object of a class contains specific values.

Let us create the list c1 and state that it is an object with class name customer.

c1 <- list(name = 'Wolfgang', salary = 100, years = 10)
class(c1) <- 'customer'
c1

A constructor is a function that creates objects. Usually, the constructor name and class name are identical. That means, we integrate the above in a function.

customer <- function(n,s,y){
  cr <- list(name = n, salary = s, years = y)
  class(cr) <- 'customer'  
  return(cr)
}
wolfi <- customer('Wolfgang', 100, 10)
print(wolfi)

Let us write a customised print function for the customer class.

print.customer <- function(obj){
  cat("Name: ", obj$name,"\nSalary: ", obj$salary)
}

print(wolfi)

This is “cool”! The function print.customer was automatically associated with the class. This is the first benefit of classes we have noticed. That means, there is a generic function print that is usable across many classes (see methods(print)).

It is possible to create new generic methods. For instance, let us create the generic function salary and implement a default function.

# generic method
salary <- function(obj) { UseMethod("salary")}

# try this for any class
salary.default <- function(obj) {
  cat("The salary is", obj$salary,".\n")
}

# use this for the customer class
salary.customer <- function(obj) {
  cat("The salary of",obj$name,"is", obj$salary,".\n")
}
salary(list(salary=77))
salary(wolfi)

Practice makes perfect

Create a generic, default and specific purchase function for the customer class, which allows a customer to buy a car.

# generic method
purchased <- function(obj) { UseMethod("purchase")}

# try this for any class
purchased <- function(obj, purchased_object) {
  obj$purchased_object <- purchased_object
  cat("The object:", obj$purchased_object,"was purchased.\n")
  return(obj)
}

# use this for the customer class
purchased <- function(obj, car) {
  obj$car <- car
  cat(obj$name, "purchased a", obj$car,".\n")
  return(obj)
}
wolfi <- purchased(wolfi,"MG ZS EV")

A class consists out of attributes (attributes(c1)) and methods. The above introduced S3 class system is probably the most popular one. Generally, object oriented programming (OOP) attempts to provide coding with a more natural language. For instance, “Wolfgang purchased an BMW”, translates into wolfi <- purchased(wolfi,"BMW").

However, there is another object oriented programming approach in R, known as R6. This one is more closely related to traditional programming languages such as C# and Java. Please see Hadley’s R6 and Chang’s documentation for more details. The above example’s translation becomes a bit more natural wolfi$purchased("BMW").

library(R6)
Customer <- R6Class(
  classname = "Customer",
  public = list(
    name = '', salary = 0, car = '',
    initialize = function(name = '', salary = 0) {
      self$name   = name; self$salary = salary
    },
    purchased = function(car) {
      self$car = car
      cat(self$name, "purchased a",self$car,"\n")
    }
))
wolfi <- Customer$new("Wolfgang",100)
wolfi$purchased("BMW")

Resources

  • Another Data Analytics tutorial Data Analytics Tutorial for Beginners - From Beginner to Pro in 10 Mins! - DataFlair (2019)
  • Brauer (2020) is a very short introduction to R
  • Field (2021) is a great book to discover statistics using R
  • Shah (2020) is a hands-on introduction to data science (Chapter 6 explains R)

Acknowledgment

This tutorial was created using RStudio, R, rmarkdown, and many other tools and libraries. The packages learnr and gradethis were particularly useful. I’m very grateful to Prof. Andy Field for sharing his discovr package, which allowed me to improve the style of this tutorial and get more familiar with learnr. Allison Horst wrote a very instructive blog “Teach R with learnr: a powerful tool for remote teaching”, which encouraged me to continue with learnr. By the way, I find her statistic illustrations amazing.

References

Brauer, Claudia. 2020. A-very-short-introduction-to-R.” GitHub. https://github.com/ClaudiaBrauer/A-very-short-introduction-to-R/blob/master/documents/A%20(very)%20short%20introduction%20to%20R.pdf.
Data Analytics Tutorial for Beginners - From Beginner to Pro in 10 Mins! - DataFlair.” 2019. DataFlair. https://data-flair.training/blogs/data-analytics-tutorial.
Field, Andy P. 2021. Discovering Statistics Using R and RStudio. Second. London: Sage.
Shah, Chirag. 2020. A Hands-on Introduction to Data Science. Cambridge University Press.

Data Analytics - Datatypes in R

Wolfgang Garn

Back to tutorials