c(1, 2, NA, 6)
Functions1: Answers
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 the NA
and use named argument matching
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.
<- 5
w <- function(y) {
f return(w + y)
}f(y = 2)
<- 5
w <- function(y) {
f <- 4
w return(w + y)
}f(y = 2)
This will return 7 because
w
is 5 and we are evaluating the function aty = 2
This will return 6 because
w
is reassigned as 4 inside the function and we are evaluating the function aty = 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)
<- 2
w <- function(y) {
f <- 3
d <- function(z) {
h 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:
- Try:
<- function(a) {
myFun1 <- 3
b myFun2(a)
}
<- function(y) {
myFun2 return(y + a + b)
}
myFun1(10)
What happens?
- Now try:
<- 1
a <- 2
b myFun1(10)
What happens?
We get an error message because
a
andb
are local tomyFun1
so the functionmyFun2
can’t find them in the global environment.We get get the value 13 because the values
a
andb
are global somyFun2
can find them and use them in its commands.