Blog of Andrés Aravena
CMB2:

Homework 4

04 March 2020. Deadline: Tuesday, 10 March, 8:30.

This week we will dive into functions. These are the key piece for the rest of the course, and will allow you to think about real life problems. We start with one question in four versions. If you look carefully, they are all essentially the same question, so if you solve the first one, the rest should be easy.

Please write the code of the following functions:

  1. smallest_value(x). Returns the smallest element in x.
  2. largest_value(x). Returns the largest element in x.
  3. place_of_smallest(x). Returns the index of the smallest element in x.
  4. place_of_largest(x). Returns the index of the largest element in x.

Make these functions using only the commands for(), if() and indices. You can also do assignments, but you cannot use the words min or max. In all cases the input is a vector called x.

You can test your function with the following code1.

x <- sample(5:20, size=10, replace=TRUE)
min(x)
smallest_value(x)

The two results must be the same.

Post Scriptum

The wise Shoaib Diaa Ahmed realized that I forgot to put the template for answers. Moreover, Shoaib told me about this. Good catch.

The template for answers is here.

Deadline: Tuesday, 10 March, 8:30.