Question 1

Consider the following simple function

v = 5
fun1 = function() {
  v = 0
  return(v)
}
fun1()
  1. Why does the final line return 0 and not 5. r ## fun1 uses the local variable v
  2. Delete line 3 in the above piece of code. Now change fun1() to allow v to be passed as an argument, i.e. we can write fun1(5). Call this function to make sure it works.

    r fun1 = function(v) { return(v) } fun1(10)

Question 2

fun2 = function(x = 10) {
  return(x)
}

fun3 = function(x) {
  return(x)
}
  1. Why does r fun2() work, but this raises an error r fun3()

    ```r

    fun3 expects an argument x, but

    we haven't given one and there is

    no default.

    ```

  2. Change fun2 so that it returns x*x.

    r fun2 = function(x = 10) { return(x * x) }

Question 3

a = 2
total = 0
for (blob in a:5) {
  total = total + blob
}
  1. In the code above, delete line 1. Now put the above code in a function called fun5, where a is passed as an argument, i.e. we can call fun5(1)

    r fun5 = function(a) { total = 0 for (blob in a:5) { total = total + blob } return(total) } fun5(1)

  2. Alter the code so that the for loop goes from a to b, rather than a to $5$. Allow b to be passed as an argument, i.e. we can call fun5(1,5). r fun5 = function(a, b) { total = 0 for (blob in a:b) { total = total + blob } return(total) } fun5(1, 5)

  3. Change fun5 so that it has default arguments of a = 1 and b = 10. Try calling fun5(5). Why do we get the answer outputted?

    r fun5 = function(a=1, b=10) { total = 0 for (blob in a:b) { total = total + blob } return(total) } fun5(5)

Solutions

Solutions are contained within this package:

vignette("solutions2", package = "jrProgramming")


jr-packages/jrProgramming documentation built on Sept. 8, 2020, 9:35 p.m.