Matrix Algebra and Linear Models

Week 1 - R Refresher

See edX

Data summary

library(UsingR, verbose=FALSE, quietly=TRUE, warn.conflicts=FALSE)
## Warning: package 'UsingR' was built under R version 3.1.3
## Warning: package 'HistData' was built under R version 3.1.3
## Loading required package: grid
## Loading required package: lattice
## Loading required package: survival
## Loading required package: splines
## Loading required package: Formula
## 
## Attaching package: 'Hmisc'
## 
## The following objects are masked from 'package:base':
## 
##     format.pval, round.POSIXt, trunc.POSIXt, units
str(father.son)
## 'data.frame':    1078 obs. of  2 variables:
##  $ fheight: num  65 63.3 65 65.8 61.1 ...
##  $ sheight: num  59.8 63.2 63.3 62.8 64.3 ...

What is the average height of the sons (don’t round off)?

mean(father.son$sheight)
## [1] 68.68407

What is the mean of the son heights for fathers that have a height of 71 inches (don’t round off your answer)?

f71 <- father.son[round(father.son$fheight) == 71,]
mean(f71$sheight)
## [1] 70.54082

Create the matrix from the vector 1:1000 like this:

X = matrix(1:1000,100,10)

What is the entry in row 25, column 3 ?

X = matrix(1:1000,100,10)
X[25, 3]
## [1] 225

Using the function cbind, create a 10 x 5 matrix with first column

x=1:10

Then columns 2x, 3x, 4x and 5x in columns 2 through 5.

What is the sum of the elements of the 7th row?

x <- 1:10
y <- cbind(x, 2*x, 3*x, 4*x, 5*x)
sum(y[7,])
## [1] 105

3a + 4b - 5c + d = 10

2a + 2b + 2c - d = 5

a -b + 5c - 5d = 7

5a + d = 4

What is the solution for c:

X <- matrix(c(3,4,-5,1,2,2,2,-1,1,-1,5,-5,5,0,0,1),4,4,byrow=TRUE)
y <- matrix(c(10,5,7,4))
solve(X, y)
##            [,1]
## [1,]  1.2477876
## [2,]  1.0176991
## [3,] -0.8849558
## [4,] -2.2389381

Load the following two matrices into R:

a <- matrix(1:12, nrow=4) b <- matrix(1:15, nrow=3)

a <- matrix(1:12, nrow=4)
b <- matrix(1:15, nrow=3)

What is the value in the 3rd row and the 2nd column of the matrix product of ‘a’ and ‘b’

m <- a %*% b
m[3,2]
## [1] 113

Multiply the 3rd row of ‘a’ with the 2nd column of ‘b’, using the element-wise vector multiplication with *.

What is the sum of the elements in the resulting vector?

sum(a[3,] * b[,2])
## [1] 113