Functions1: Answers

Warning

Make sure that you try the exercises yourself first before looking at the answers

Function Arguments

Look at the help file for the function mean().

How many arguments does the function have?

What types of vectors are accepted?

What is the default setting for dealing with NA values?

Three arguments (plus further arguments).

Numerical and logical vectors are accepted.

The default setting is to NOT remove NA (missing) values.

Use the function mean() to calculate the mean of the following values:

Note

note the NA and use named argument matching

c(1, 2, NA, 6)
mean(x = c(1, 2, NA, 6), na.rm = TRUE)
[1] 3

Do Q2 again but rearrange the arguments.

mean(na.rm = TRUE, x = c(1, 2, NA, 6))
[1] 3

Do Q2 again using positional matching.

mean(c(1, 2, NA, 6), 0, TRUE)
[1] 3

Determine the class of mean() using class().

class(mean)
[1] "function"

The class is function.

Determine the class of mean() using str().

str(mean)
function (x, ...)  

The class is function.

Determine the class of the value output in Q4 using class().

class(mean(c(1, 2, NA, 6), 0, TRUE))
[1] "numeric"

The class is numeric

Determine the class of the value output in Q4 using str().

str(mean(c(1, 2, NA, 6), 0, TRUE))
 num 3

The num means the class is numeric.

Function environment and scoping

For each of the following sets of commands, give the value that will be returned by the last command. Try to answer without using R.

w <- 5
f <- function(y) {
  return(w + y)
}
f(y = 2)
w <- 5
f <- function(y) {
  w <- 4
  return(w + y)
}
f(y = 2)
  1. This will return 7 because w is 5 and we are evaluating the function at y = 2

  2. This will return 6 because w is reassigned as 4 inside the function and we are evaluating the function at y = 2.

Among the variables w, d, and y, which are global to f() and which are local? What is the value of z when executing f(w)

w <- 2
f <- function(y) {
  d <- 3
  h <- function(z) {
    return(z + d)
  }
  return(y * h(y))
}

The object w is global to f() while d and y are local to f().

z is 2, because it takes the value of y when executing h(y) in function f(), which takes the value of global variable w when executing f(w)

Do the following in R:

  1. Try:
myFun1 <- function(a) {
  b <- 3
  myFun2(a)
}

myFun2 <- function(y) {
  return(y + a + b)
}

myFun1(10)

What happens?

  1. Now try:
a <- 1
b <- 2
myFun1(10)

What happens?

  1. We get an error message because a and b are local to myFun1 so the function myFun2 can’t find them in the global environment.

  2. We get get the value 13 because the values a and b are global so myFun2 can find them and use them in its commands.