2.11 Coding Exercises
The
stringr
package contains a number of functions for working with strings. For this problem create the following character vector in R<- c("economics", "econometrics", "ECON 4750") x
Install the
stringr
package and use thestr_length
function in the package in order to calculate the length (number of characters) in each element ofx
.For this problem, we are going to write a function to calculate the sum of the numbers from 1 to \(n\) where \(n\) is some positive integer. There are actually a lot of different ways to do this.
Approach 1: write a function called
sum_one_to_n_1
that uses the R functionsseq
to create a list of numbers from 1 to \(n\) and then the functionsum
to sum over that list.Approach 2: The sum of numbers from 1 to \(n\) is equal to \(n(n+1)/2\). Use this expression to write a function called
sum_one_to_n_2
to calculate the sum from 1 to \(n\).
Approach 3: A more brute force approach is to create a list of numbers from 1 to \(n\) (you can use
seq
here) and add them up using afor
loop — basically, just keep track of what the current total is and add the next number to the total in each iteration of the for loop. Write a function calledsum_one_to_n_3
that does this.
Hint: All of the functions should look like
<- function(n) { sum_one_to_n # do something }
Try out all three approaches that you came up with above for \(n=100\). What is the answer? Do you get the same answer using all three approaches?
The Fibonacci sequence is the sequence of numbers \(0,1,1,2,3,5,8,13,21,34,55,\ldots\) that comes from starting with \(0\) and \(1\) and where each subsequent number is the sum of the previous two. For example, the 5 in the sequence comes from adding 2 and 3; the 55 in the sequence comes from adding 21 and 34.
Write a function called
fibonacci
that takes in a numbern
and computes the nth element in the Fibonacci sequence. For examplefibonacci(5)
should return3
andfibonacci(8)
should return13
.Consider an alternative sequence where, starting with the third element, each element is computed as the sum of the previous two elements (the same as with the Fibonacci sequence) but where the first two elements can be arbitrary. Write a function
alt_seq(a,b,n)
wherea
is the first element in the sequence,b
is the second element in the sequence, andn
is which element in the sequence to return. For example, if \(a=3\) and \(b=7\), then the sequence would be \(3,7,10,17,27,44,71,\ldots\) andalt_seq(a=3,b=7,n=4) = 17
.
Write a function
prime
that takesn
as an argument and returns a vector of all the prime numbers from \(1\) to \(n\).Base
R
includes a data frame callediris
. This is data about iris flowers (you can read the details by running?iris
).How many observations are there in the entire data frame?
Calculate the average
Sepal.Length
across all observations iniris
.Calculate the average
Sepal.Width
among thesetosa
iris species.Sort
iris
byPetal.Length
and print the first 10 rows.