rukÂ·si

# ðŸ“Š R - Matrices

Updated at 2017-10-13 17:54

Matrices are two dimensional vectors.

``````# fill with 0, 3 rows high, 4 columns wide.
matrix(0, nrow=3, ncol=4)
#      [,1] [,2] [,3] [,4]
# [1,]    0    0    0    0
# [2,]    0    0    0    0
# [3,]    0    0    0    0
``````

You can use vector to fill in a matrix. By default, matrix is filled from top to bottom and left to right.

``````a <- 1:12
matrix(a, 3, 4)
#      [,1] [,2] [,3] [,4]
# [1,]    1    4    7   10
# [2,]    2    5    8   11
# [3,]    3    6    9   12
``````

Pass in fourth argument to fill from left to right and top to bottom.

``````a <- 1:12
matrix(a, 3, 4, byrow=TRUE)
#      [,1] [,2] [,3] [,4]
# [1,]    1    2    3   4
# [2,]    5    6    7   8
# [3,]    9    10   11  12
``````

Dimension function `dim` can be used to transform vector into a matrix. Note that `dim` also returns current dimensions.

``````plank <- 1:8
dim(plank) <- c(2, 4)
print(plank)
#      [,1] [,2] [,3] [,4]
# [1,]    1    3    5    7
# [2,]    2    4    6    8
``````

Matrix access.

``````#      [,1] [,2] [,3] [,4]
# [1,]    1    3    5    7
# [2,]    2    4    6    8

# Single element.
plank[2, 3]
# [1] 6

# Assignment to a single element.
plank[1, 4] <- 0

# Get one row.
plank[2,]
# [1] 2 4 6 8

# Get one column.
plank[, 4]
# [1] 7 8

# Get sub matrix from columns 2, 3 and 4.
plank[, 2:4]
#      [,1] [,2] [,3]
# [1,]    3    5    7
# [2,]    4    6    8
``````

Plotting matrices.

``````# Each point is 1 meter above sea level on a beach.
elevation <- matrix(1, 10, 10)

# We dug a hole in the beach.
elevation[4, 6] <- 0

# Generating a contour map.
contour(elevation)

# Generating a 3D perspective plot.
persp(elevation)

# Same plot but do not expand to full height.
persp(elevation, expand = 0.2

# R has some sample data you can use.
# volcano is 3D map of a dormant New Zealand volcano.
# 87x61 matrix with elevation values.
contour(volcano)
persp(volcano, expand=0.2)

# Generating a heap map
image(volcano)
``````

# Sources

• Google Developers R Programming Videos
• Try R