Abstract
This is an assignment from the results of studying R Fundamental. There are several questions and tasks that I have answered. Hopefully it is useful.library(DT)
cars <- read.csv("cars.csv", header = TRUE, sep = ",")
datatable(cars, caption = "Cars Dataset")
library(glue)
glue("There are {nrow(cars)} rows in the cars dataset.")
## There are 428 rows in the cars dataset.
glue("There are {ncol(cars)} columns in the cars dataset.")
## There are 19 columns in the cars dataset.
glue("There are {length(unique(cars$cylenders))} unique numbers of cylinders in the cars dataset.")
## There are 8 unique numbers of cylinders in the cars dataset.
glue("The average horsepower of cars is {mean(cars$horsepower)}")
## The average horsepower of cars is 215.885514018692
glue("The maximum horsepower is {max(cars$horsepower)}")
## The maximum horsepower is 500
glue("The most expensive car is {cars$name[which.max(cars$Price)]}")
## The most expensive car is Porsche 911 GT2 2dr
colnames(cars)[colnames(cars) == "name"] <- "car name"
datatable(cars, caption = "Column 'name' has been changed to 'car name'")
glue("There are {sum(cars$sports_car)} sports cars in the dataset.")
## There are 49 sports cars in the dataset.
make a subset of the data that has the car name and the price and name the new subsetted data frame car pricing.
car_pricing <- cars[, c("car name", "Price")]
datatable(car_pricing, caption = "Subset of the data that has the car name and the price")
create a function called pricing category that returns “Budget Car” if the cars are less than 20,000 USD,” Suitable Car ” is the car is more than 20,000 and less than 35 000 and finally an expensive car for cars more than 35000.
pricing_category <- function(price){
if(price < 20000){
return("Budget Car")
} else if(price >= 20000 & price < 35000){
return("Suitable Car")
} else {
return("Expensive Car")
}
}
create a column named category on the subset using a for loop and pricing category function.
car_pricing$category <- NA
for(i in 1:nrow(car_pricing)){
car_pricing$category[i] <- pricing_category(car_pricing$Price[i])
}
How many Budget cars, suitable cars, and expensive cars we have?
glue("There are {sum(car_pricing$category == 'Budget Car')} Budget Cars, {sum(car_pricing$category == 'Suitable Car')} Suitable Cars, and {sum(car_pricing$category == 'Expensive Car')} Expensive Cars.")
## There are 98 Budget Cars, 193 Suitable Cars, and 137 Expensive Cars.