Description
QUESTION 1 Take a look at the ‘iris’ dataset that comes with R. The data can be loaded with the code:
library(datasets) data(iris)
There will be an object called ‘iris’ in your workspace. In this dataset, what is the mean of ‘Sepal.Length’ for the species virginica? Please round your answer to the nearest whole number.
Solution
7
For the solution we can use any of the following codes
mean(iris$Sepal.Length[iris$Species==”virginica”])
## [1] 6.588
or
tapply(iris$Sepal.Length,iris$Species,mean)
## setosa versicolor virginica
## 5.006 5.936 6.588
or
with(iris,tapply(Sepal.Length,Species,mean))
## setosa versicolor virginica
## 5.006 5.936 6.588
or
sapply(split(iris$Sepal.Length, iris$Species), mean)
## setosa versicolor virginica
## 5.006 5.936 6.588
QUESTION 2 Continuing with the ‘iris’ dataset from the previous Question, what R code returns a vector of the means of the variables ‘Sepal.Length’, ‘Sepal.Width’, ‘Petal.Length’, and ‘Petal.Width’? Solution
apply(iris[, 1:4], 2, mean)
## Sepal.Length Sepal.Width Petal.Length Petal.Width
## 5.843333 3.057333 3.758000 1.199333
QUESTION 3 Load the ‘mtcars’ dataset in R with the following code
library(datasets) data(mtcars)
1
How can one calculate the average miles per gallon (mpg) by number of cylinders in the car (cyl)? Select all that apply. Solution
with(mtcars, tapply(mpg, cyl, mean))
## 4 6 8
## 26.66364 19.74286 15.10000
tapply(mtcars$mpg, mtcars$cyl, mean)
## 4 6 8
## 26.66364 19.74286 15.10000
sapply(split(mtcars$mpg, mtcars$cyl), mean)
## 4 6 8
## 26.66364 19.74286 15.10000
QUESTION 4 Continuing with the ‘mtcars’ dataset from the previous Question, what is the absolute difference between the average horsepower of 4-cylinder cars and the average horsepower of 8-cylinder cars? Solution
127 for solution we can use any equations used in equation 1 or 3.
eg.
mean(mtcars$hp[mtcars$cyl==”8″]) – mean(mtcars$hp[mtcars$cyl==”4″])
## [1] 126.5779
QUESTION 5 If you run
debug(ls)
what happens when you next call the ‘ls’ function?
Solution
Execution of ‘ls’ will suspend at the beginning of the function and you will be in the browser.
2




Reviews
There are no reviews yet.