Homework 1: Vectors, Matrices and Graphs

Vectors

Enter the following commands, and then briefly explain what they do

a)
x <- c(0,1,2,3,4,5,6,7,8,9,10)
b)
x <- 0:10
c)
x <- seq(0,10,2)
d)
x <- seq(10,0,-0.5)
e)
x > 5
f)
x[x>5]
g)
x / 2
h)
x %/% 2

Create matrices

Enter the statements necessary to create the following matrices:

\begin{equation} a = \begin{bmatrix} 1 & 5 & 5 \\ -1 & 3 & 6 \\ 2 & 0 & 2 \end{bmatrix} \quad b = \begin{bmatrix} 2 & -3 & 5 \\ 1 & 0 & 6 \\ 2 & 3 & 1 \end{bmatrix} \quad c = \begin{bmatrix} 5 & 1 & 9 & 0 \\ 4 & 0 & 6 & -2\\ 3 & -1 & 2 & 4 \end{bmatrix} \quad d = \begin{bmatrix} 3 & 2 & 5 \\ 4 & 1 & 3 \\ 0 & 2 & 1\\ -2 & 5 & 6 \end{bmatrix} \end{equation}

Matrix math

Using the matrices from above, compute the following using R, and record the results. If you receive an error message rather than a numerical result, explain the error.

a)
a + b
b)
a - 2*b
c)
(a - 2)*b
d)
a^2
e)
sqrt(a)
f)
t(c)
g)
c + d
h)
t(c) + d
i)
c %*% d
j)
a - 2 * diag(1,3)
k)
a - matrix(1,3,3)

More Matrix math

Using the matrices from #1, enter the following commands, and then briefly explain what they do

a)
a[1,]
b)
b[,2]
c)
rbind(a,b)
d)
cbind(a,b)
e)
a[c(1,2),] <- a[c(2,1),]

Order of operations

Which two lines of code are equivalent?

a)
x = aa + bb * cc + dd / ee;
b)
x = (aa + bb) * (cc + dd) / ee;
c)
x = aa + (bb * cc) + (dd / ee);
d)
x = (aa + (bb * cc) + dd) / ee;

Graphics

Use the ggplot2 package to create a plot that reveal something interesting about either the diamonds or mpg datasets (both are installed when you run library(ggplot2)). For each graph, include the code you used to create the plot, and a one paragraph description of what you found interesting.

Back to top | E-mail Schwilk