This is Quiz 2 from Coursera’s R Programming class within the Data Science Specialization. This publication is intended as a learning resource, all answers are documented and explained. Datasets are available in R packages.
1. Suppose I define the following function in R
cube <- function(x, n) {
x^3
}
cube(3)
## [1] 27
Function cubes the input.
2. The following code will produce a warning in R.
x <- 1:10
if(x > 5) {
x <- 0
}
## Warning in if (x > 5) {: the condition has length > 1 and only the first
## element will be used
Why?
R will automatically use the first element of the vector.
3. Consider the following function
f <- function(x) {
g <- function(y) {
y + z
}
z <- 4
x + g(x)
}
and then run
z <- 10
f(3)
## [1] 10
Run it.
4. Consider the following expression:
x <- 5
y <- if(x < 3) {
NA
} else {
10
}
y
## [1] 10
Run it.
5. Consider the following R function
h <- function(x, y = NULL, d = 3L) {
z <- cbind(x, d)
if(!is.null(y))
z <- z + y
else
z <- z + f
g <- x + y / z
if(d == 3L)
return(g)
g <- g + 10
g
}
6. What is an environment in R?
7. The R language uses what type of scoping rule for resolving free variables?
8. How are free variables in R functions resolved?
10. In R, what is the parent frame?