automobile<-mtcarsData Programming
Homework 1
Solutions
Submit a .html file created using Quarto via e-classroom. A sample is attached. Display all code (packages,input) and output.
Transform the dataframe automobile
- Move rownames to a column cars.name, remove rownames.
- Add a column named l/100km whose values are based on column mpg, then delete column mpg.
- Change the am column to a factor with levels Automatic and Manual.
# solve 1-3 here
library(dplyr)
library(tibble)
# 1st task
automobile$cars.name <- rownames(automobile)
rownames(automobile) <- c(1:nrow(automobile))
# 2nd task
automobile$L100km <- (235.214583 / automobile$mpg)
automobile <- automobile %>% select(-mpg)
# 3rd task
automobile$am <- automobile$am %>% factor(levels = c(0, 1), labels = c("Automatic", "Manual"))After the transformation display the data frame as a tibble then answer these questions independently.
library(tidyverse)
as.tibble(automobile)# A tibble: 32 × 12
cyl disp hp drat wt qsec vs am gear carb cars.name L100km
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <fct> <dbl> <dbl> <chr> <dbl>
1 6 160 110 3.9 2.62 16.5 0 Manual 4 4 Mazda RX4 11.2
2 6 160 110 3.9 2.88 17.0 0 Manual 4 4 Mazda RX… 11.2
3 4 108 93 3.85 2.32 18.6 1 Manual 4 1 Datsun 7… 10.3
4 6 258 110 3.08 3.22 19.4 1 Autom… 3 1 Hornet 4… 11.0
5 8 360 175 3.15 3.44 17.0 0 Autom… 3 2 Hornet S… 12.6
6 6 225 105 2.76 3.46 20.2 1 Autom… 3 1 Valiant 13.0
7 8 360 245 3.21 3.57 15.8 0 Autom… 3 4 Duster 3… 16.4
8 4 147. 62 3.69 3.19 20 1 Autom… 4 2 Merc 240D 9.64
9 4 141. 95 3.92 3.15 22.9 1 Autom… 4 2 Merc 230 10.3
10 6 168. 123 3.92 3.44 18.3 1 Autom… 4 4 Merc 280 12.3
# ℹ 22 more rows
- What is the average number of gears?
- Return the rows with cars with horsepower between 200 and 400.
- Which car is most fuel efficient car among 6 cylinder cars?
# solve 4-6 here
# 4
mean(automobile$gear) [1] 3.6875
# 5
automobile[c(automobile$hp>200 & automobile$hp<400),] cyl disp hp drat wt qsec vs am gear carb cars.name
7 8 360 245 3.21 3.570 15.84 0 Automatic 3 4 Duster 360
15 8 472 205 2.93 5.250 17.98 0 Automatic 3 4 Cadillac Fleetwood
16 8 460 215 3.00 5.424 17.82 0 Automatic 3 4 Lincoln Continental
17 8 440 230 3.23 5.345 17.42 0 Automatic 3 4 Chrysler Imperial
24 8 350 245 3.73 3.840 15.41 0 Automatic 3 4 Camaro Z28
29 8 351 264 4.22 3.170 14.50 0 Manual 5 4 Ford Pantera L
31 8 301 335 3.54 3.570 14.60 0 Manual 5 8 Maserati Bora
L100km
7 16.44857
15 22.61679
16 22.61679
17 16.00099
24 17.68531
29 14.88700
31 15.68097
# 6
(automobile %>% .[c(.$cyl == 6),] %>% .[order(.$"L100km", decreasing = F),])[1,] cyl disp hp drat wt qsec vs am gear carb cars.name L100km
4 6 258 110 3.08 3.215 19.44 1 Automatic 3 1 Hornet 4 Drive 10.99134