automobile <- mtcarsDataProg - Homework1
Loading the dataset ‘mtcars’ into the dataframe ‘automobile’:
1. Moving rownames to a column ‘cars.name’ and removing rownames:
automobile$cars.name <- rownames(automobile)
rownames(automobile)<- NULL2. Adding a column named ‘L100km’ whose values are based on the column ‘mpg’ and deleting ‘mpg’:
automobile$L100km <- automobile$mpg
automobile$mpg <- NULL3. Changing the ‘am’ column to a factor with levels Automatic and Manual:
automobile$am <- factor(automobile$am, levels = c(0,1), labels = c("Automatic","Manual"))Displaying the dataframe ‘automobile’ as tibble:
library(tibble)
automobileTibble<- as_tibble(automobile)
print(automobileTibble)# 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 21
2 6 160 110 3.9 2.88 17.0 0 Manual 4 4 Mazda RX… 21
3 4 108 93 3.85 2.32 18.6 1 Manual 4 1 Datsun 7… 22.8
4 6 258 110 3.08 3.22 19.4 1 Autom… 3 1 Hornet 4… 21.4
5 8 360 175 3.15 3.44 17.0 0 Autom… 3 2 Hornet S… 18.7
6 6 225 105 2.76 3.46 20.2 1 Autom… 3 1 Valiant 18.1
7 8 360 245 3.21 3.57 15.8 0 Autom… 3 4 Duster 3… 14.3
8 4 147. 62 3.69 3.19 20 1 Autom… 4 2 Merc 240D 24.4
9 4 141. 95 3.92 3.15 22.9 1 Autom… 4 2 Merc 230 22.8
10 6 168. 123 3.92 3.44 18.3 1 Autom… 4 4 Merc 280 19.2
# ℹ 22 more rows
4. Average number of gears:
avgGear<-mean(automobile$gear)
print(avgGear)[1] 3.6875
5. Rows with cars with horsepower between 200 and 400:
selRows <- automobile[automobile$hp >= 200 & automobile$hp <= 400, ]
print(selRows) 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 14.3
15 10.4
16 10.4
17 14.7
24 13.3
29 15.8
31 15.0
6. The car that is most fuel-efficient among 6 cylinder cars:
#Subsetting the dataframe to only include 6-cylinder cars
sixCylCars <- automobile[automobile$cyl == 6, ]
#Finding the row with highest fuel-efficiency
fuelEffCar <- sixCylCars[which.max(sixCylCars$L100km),]
print(fuelEffCar) 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 21.4