First Steps: Exercise solutions

c(1:20,19:1)
##  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 19 18 17
## [24] 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1
rep(c(4,6,3), times = 10)
##  [1] 4 6 3 4 6 3 4 6 3 4 6 3 4 6 3 4 6 3 4 6 3 4 6 3 4 6 3 4 6 3
rep(c(7,6,1), times=c(3,4,2))
## [1] 7 7 7 6 6 6 6 1 1
sum((10:100)^3 + 4*(10:100)^2)
## [1] 26852735

or

i <- 10:100 ; sum(i^3 + 4*(i^2))
## [1] 26852735

More Vectors: Exercise solutions

p <- c(1.8, 3.2, -3.3, 5.4, 8.8)

p[1:3]
## [1]  1.8  3.2 -3.3
p[-3]
## [1] 1.8 3.2 5.4 8.8
p[order(p)]
## [1] -3.3  1.8  3.2  5.4  8.8
c(10, 20, 30) + 1:9 
## [1] 11 22 33 14 25 36 17 28 39
sum(1, FALSE)
## [1] 1
sum("1",4)
## Error in sum("1", 4): invalid 'type' (character) of argument
paste("Stage", 4:10)
## [1] "Stage 4"  "Stage 5"  "Stage 6"  "Stage 7"  "Stage 8"  "Stage 9" 
## [7] "Stage 10"
sum(sample(1:100, 200, replace = T) > 50)
## [1] 102
mc <- replicate(5000,sum(sample(1:100, 200, replace = T) > 50))
mean(mc)
## [1] 99.877
var(mc)
## [1] 51.45976
sqrt(var(mc)/length(mc))
## [1] 0.1014493
library(ggplot2)
qplot(x = mc, binwidth=1, xlab = "Draws greather than 50", ylab="Count")

Subsets and Functions: Exercise Solutions

Exercise 1

letters[1:26 %% 3 == 0]
## [1] "c" "f" "i" "l" "o" "r" "u" "x"
letters[c(F,F,T)]
## [1] "c" "f" "i" "l" "o" "r" "u" "x"
letters[3*(1:(26/3))]
## [1] "c" "f" "i" "l" "o" "r" "u" "x"

Exercise 3

isSquareNumber <- function(x) {
  x <- ifelse(x > 0, x, NA)
  (sqrt(x) %% 1) == 0
}

r <- 18354:18796

any(isSquareNumber(r))
## [1] TRUE
r[which(isSquareNumber(18354:18796))]
## [1] 18496 18769

Exercise 4

isPrimeNumber <- function(x) {
  if(x == 2) {
    TRUE
  } else if (any(x %% 2:(x-1) == 0)) {
    FALSE
  } else {
    TRUE
  }
}

Matrices: Exercise solutions

Exercise 1

hilbert <- function(n) {
  i <- matrix(rep(1:n,times=n),nrow=n)
  j <- t(i)
  1 / (i + j - 1)
}

#or

hilbert <- function(n) {
  i <- replicate(n, 1:n)
  j <- t(i)
  1 / (i + j - 1)
}

solve(hilbert(5))
##       [,1]   [,2]    [,3]    [,4]   [,5]
## [1,]    25   -300    1050   -1400    630
## [2,]  -300   4800  -18900   26880 -12600
## [3,]  1050 -18900   79380 -117600  56700
## [4,] -1400  26880 -117600  179200 -88200
## [5,]   630 -12600   56700  -88200  44100

Exercise 2

d <- as.matrix(read.table("http://goo.gl/dxjUME",header=T))

y <- log(d[,"wage"])
X <- cbind(intercept = 1, d[, c("educ", "IQ","expr")])
n <- nrow(X)
k <- ncol(X)

#coefficients
b <- solve(t(X) %*% X) %*% t(X) %*% y 

#residuals
r <- y - (X %*% b)

#variance covariance matrix (homoscedasticity)
sigma_2 <- sum(r^2) / (n - k)
vcov <- sigma_2 * solve((t(X) %*% X))

#standard errors
se <- sqrt(diag(vcov))

#t statistics
t <- b / se

#p values
2 * (1 - pt(t, k - 1))
##                   [,1]
## intercept 4.891191e-05
## educ      8.542239e-04
## IQ        3.210629e-02
## expr      5.495365e-03