Homework 1 Solutions

Ch. 3, Q1

x <- c("economics", "econometrics", "ECON 4750")

library(stringr)

str_length(x)
[1]  9 12  9

Ch. 3, Q2

Approach 1

sum_one_to_n_1 <- function(n) {
  one_to_n <- seq(1,n)
  sum(one_to_n)
}

Approach 2

sum_one_to_n_2 <- function(n) {
  out <- n*(n+1)/2
  out
}

Approach 3

sum_one_to_n_3 <- function(n) {
  out <- 0
  for (i in 1:n) {
    out <- out + i
  }
  out
}

Let’s check that they all give the same result.

sum_one_to_n_1(100)
[1] 5050
sum_one_to_n_2(100)
[1] 5050
sum_one_to_n_3(100)
[1] 5050

Ch. 3, Q3

Part a

fibonacci <- function(n) {

  # handle cases where n=1 or 2
  if (n == 1) {
    return(0)
  }

  if (n==2) {
    return(1)
  }

  # main code
  fib_seq <- c(0,1)

  for (i in 3:n) {
    fib_seq[i] <- fib_seq[i-1] + fib_seq[i-2]
  }

  fib_seq[n]
}
fibonacci(5)
[1] 3
fibonacci(8)
[1] 13

Part b

alt_seq <- function(a,b,n) {
  # handle cases where n=1 or 2
  if (n == 1) {
    return(a)
  }

  if (n==2) {
    return(b)
  }

  # main code
  this_seq <- c(a,b)

  for (i in 3:n) {
    this_seq[i] <- this_seq[i-1] + this_seq[i-2]
  }

  this_seq[n]
}
alt_seq(3,7,4)
[1] 17

Ch. 3, Q5

Part a

nrow(iris)
[1] 150

Part b

mean(iris$Sepal.Length)
[1] 5.843333

Part c

mean(subset(iris, Species=="setosa")$Sepal.Width)
[1] 3.428

Part d

sorted_iris <- iris[order(iris$Petal.Length),]
sorted_iris[1:10,]
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
23          4.6         3.6          1.0         0.2  setosa
14          4.3         3.0          1.1         0.1  setosa
15          5.8         4.0          1.2         0.2  setosa
36          5.0         3.2          1.2         0.2  setosa
3           4.7         3.2          1.3         0.2  setosa
17          5.4         3.9          1.3         0.4  setosa
37          5.5         3.5          1.3         0.2  setosa
39          4.4         3.0          1.3         0.2  setosa
41          5.0         3.5          1.3         0.3  setosa
42          4.5         2.3          1.3         0.3  setosa