This is a quiz examining different R coding language using a dataset containing speed and distance of cars.
This code loads the cars dataset from the
datasets package. This is a special package - by loading
the datasets package, we automatically load a number of toy
datasets used for teaching R. Run this code chunk to load
the data in your environment.
library(datasets)
head(cars)
## speed dist
## 1 4 2
## 2 4 10
## 3 7 4
## 4 7 22
## 5 8 16
## 6 9 10
head() is a good function to quickly visualize your
data.
# 1. compute the mean speed of the car
avrspeed <- mean(cars$speed)
avrspeed
## [1] 15.4
# 2. compute the max distance of the car
max(cars$dist)
## [1] 120
maxdis <- max(cars$dist)
maxdis
## [1] 120
# 3. add a new variable to the cars dataset called "mult" that is the product of speed and distance
cars$mult <- (cars$speed * cars$dist)
# 4. compute the minumun of this new column
min(cars$mult)
## [1] 8
minmult <- min(cars$mult)
minmult
## [1] 8
# 5. create a NEW dataset where all rows in which speed is less than 10 to 0
cars2 <- subset(cars, cars$speed < 10)
# 6. compute the mean of speed in this new dataset
mean(cars2$speed)
## [1] 6.5
avrspeedcars2 <- mean(cars2$speed)
avrspeedcars2
## [1] 6.5
Go back to the original cars dataset for these
visualizations.
# 7. plot a histogram of speed
hist(cars$speed,
main = "Histogram of speed",
xlab = "Speed",
col = "red",
freq = TRUE)
# 8. plot a histogram of distance and add the title "Car Distance"
hist(cars$dist,
main = "Car Distance",
xlab = "Distance",
col = "blue",
freq = TRUE)
# 9. plot speed versus distance
plot(cars$speed,cars$dist,
xlab="speed",
ylab="distance")
# 10. add axis labels and a title to this plot
plot(cars$speed,cars$dist,
xlab="speed",
ylab="distance",
main = "Speed vs. Distance"
)
Knit your document to a .html file. Submit this knitted document on Canvas.