**Copy and paste the following code to your R Studio platform or R version:**

# Matrices and Frequency Tables

library(datasets)

object.size(mtcars)

mt.cars.mat <- as.matrix(mtcars)

object.size(mt.cars.mat)

# This is the second most important difference between a matrix and a data frame (size)

# The first one is that a data frame can contain columns of different types

# Create a matrix from scratch

m1 <- matrix(1:100, ncol = 5)

head(m1)

class(m1)

# Notice the difference

m1 <- matrix(1:100, ncol = 5, byrow = TRUE)

head(m1)

dim(m1)

# Subsetting is the same as in the data frames

m1[ ,c(1,2)]

m1[1:5, c(1,2,3)]

# Getting the diagonal elements

diag(m1)

# Nice functionalities with aggregate functions

# (they are avaialable in data frames as well)

rowSums(m1)

rowMeans(m1)

colSums(m1)

colMeans(m1)

cumsum(m1)

head(mtcars)

# Count the different frequencies of the cyl column

table(mtcars$cyl)

tb <- table(mtcars$cyl, mtcars$vs)

tb

class(tb)

# In this way, we can see the gear per cyl

# The first argument goes into the columns of the resulted table

table(mtcars$cyl, mtcars$gear)

# Let’s automate the solution

tb <- table(mtcars$cyl, mtcars$gear)

result <- as.data.frame.matrix(tb)

result

# Suppose we search for the intersection of 6 cylinders and 4 gears

result[rownames(result) == “6”, “4”]

# Merging data frames

set.seed(100)

df1 <- data.frame(FruitId = c(1:10),

Subject = sample(c(“Apple”, “Banana”, “Mongo”), 10, replace = TRUE))

df1

df2 <- data.frame(FruitNum = c(2,4,6,12),

Cuisine = sample(c(“Chinese”, “Mexican”, “Italian”), 4, replace = TRUE))

df2

merge(df1, df2, by.x = “FruitId”, by.y = “FruitNum”)

# By default, we get the rows that are common (inner join)

# there are other types of join, like outer, right, or left,

# where we keep all rows, all rows from the right data set

# all rows from the left data set, respectively:

merge(df1, df2, by.x = “FruitId”, by.y = “FruitNum”, all = TRUE)

merge(df1, df2, by.x = “FruitId”, by.y = “FruitNum”, all.y = TRUE)

merge(df1, df2, by.x = “FruitId”, by.y = “FruitNum”, all.x = TRUE)