Skip to content

Week 3 Quiz:R Programming(Data Science Specialization):Answers2025

Question 1

Mean of Sepal.Length for species virginica (rounded to nearest whole number)

7

Explanation:

library(datasets)
data(iris)
mean(iris$Sepal.Length[iris$Species == "virginica"])

= 6.588, which rounds to 7.


Question 2

Which R code returns a vector of means for the variables Sepal.Length, Sepal.Width, Petal.Length, and Petal.Width?

apply(iris[, 1:4], 2, mean)
❌ rowMeans(iris[, 1:4])
❌ apply(iris, 2, mean)
❌ colMeans(iris)
❌ apply(iris[, 1:4], 1, mean)
❌ apply(iris, 1, mean)

Explanation:
apply(data[, 1:4], 2, mean) applies the mean function across columns (2 = MARGIN for columns).
Alternatively, colMeans(iris[, 1:4]) would also work, but since not listed correctly, the intended correct answer is the apply() one.


Question 3

Average mpg by cyl in mtcars

with(mtcars, tapply(mpg, cyl, mean))
sapply(split(mtcars$mpg, mtcars$cyl), mean)
tapply(mtcars$mpg, mtcars$cyl, mean)
❌ Others

Explanation:
These three expressions correctly calculate group means for each cylinder group.


Question 4

Absolute difference between average horsepower (hp) of 4-cylinder and 8-cylinder cars

126

Explanation:

library(datasets)
data(mtcars)
abs(mean(mtcars$hp[mtcars$cyl == 4]) - mean(mtcars$hp[mtcars$cyl == 8]))

= |82.636 – 209.214| = 126.578 ≈ 126


Question 5

If you run debug(ls), what happens when you next call ls()?

Execution of ‘ls’ will suspend at the beginning of the function and you will be in the browser.
❌ The ‘ls’ function will execute as usual.
❌ The ‘ls’ function will return an error.
❌ You will be prompted for a line.

Explanation:
debug() sets a breakpoint at the start of a function. The next time it’s called, R enters debug mode (browser) before executing.


🧾 Summary Table

Q# ✅ Correct Answer Key Concept
1 7 Mean by subset condition
2 apply(iris[, 1:4], 2, mean) Apply over columns
3 with(…tapply…), sapply(split…), tapply(…) Group means
4 126 Mean difference by group
5 Suspends at function start (browser) Debugging in R