x <- c("economics", "econometrics", "ECON 4750")
library(stringr)
str_length(x)[1] 9 12 9
x <- c("economics", "econometrics", "ECON 4750")
library(stringr)
str_length(x)[1] 9 12 9
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
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
Part a
is_prime <- function(x) {
# handle 1 (which is not prime)
if (x == 1) {
return(FALSE)
}
# given code below, 2 and 3 are also edge cases that we should handle
# explicitly (both are prime)
if (x == 2 | x == 3) {
return(TRUE)
}
# check if x is divisible by any number from 2 to the square root of x
# (above the square root of x, we would have already caught that it factors)
for (i in 2:floor(sqrt(x))) {
if (x %% i == 0) {
# if we find a factor, it's not prime and we can immediately
# return FALSE
return(FALSE)
}
}
# if we didn't find any factors, then x is prime
return(TRUE)
}As some examples, consider
is_prime(7)[1] TRUE
is_prime(10)[1] FALSE
Part b
prime <- function(n) {
primes <- c()
for (i in 1:n) {
if (is_prime(i)) {
primes <- c(primes, i)
}
}
primes
}Check that this works
prime(100) [1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
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
quadratic_solver <- function(a, b, c) {
neg_root <- (-b - sqrt(b^2 - 4*a*c)) / (2*a)
pos_root <- (-b + sqrt(b^2 - 4*a*c)) / (2*a)
out <- list(neg_root = neg_root, pos_root = pos_root)
out
}
quadratic_solver(1,4,3)$neg_root
[1] -3
$pos_root
[1] -1