data(mtcars)
#Create different vector for each car and mpg
v1 <- mtcars["Merc 450SL", "mpg"]
v2 <- mtcars["Fiat 128", "mpg"]
v3 <- mtcars["Ferrari Dino", "mpg"]
#Creates Data Frame with a check to see if successful
subset_1 <- as.data.frame(rbind(v1, v2, v3))
is.data.frame(subset_1)
## [1] TRUE
#Adds row and column names
rownames(subset_1) <- c("Merc 450SL", "Fiat 128", "Ferrari Dino")
colnames(subset_1) <- c("mpg")
print(subset_1)
## mpg
## Merc 450SL 17.3
## Fiat 128 32.4
## Ferrari Dino 19.7
subset_1$FuelEfficiency <- ifelse(subset_1$mpg >= 21, "Good", "Bad")
print(subset_1)
## mpg FuelEfficiency
## Merc 450SL 17.3 Bad
## Fiat 128 32.4 Good
## Ferrari Dino 19.7 Bad
#Creates a new subset with the necessary variables to rank
s1 <- mtcars["Merc 450SL", c("hp","disp")]
s2 <- mtcars["Fiat 128", c("hp","disp")]
s3 <- mtcars["Ferrari Dino", c("hp","disp")]
subset_2 <- as.data.frame(rbind(s1,s2,s3))
#Creates a column with the PowerRating of each car
subset_2$PowerRating <- subset_2$hp / subset_2$disp
#Ranks the three different cars based on PowerRating
subset_2$Ranking <- rank(-subset_2$PowerRating)
#Adds the ranking to the original subset
subset_1$PowerRating = subset_2$Ranking
print(subset_1)
## mpg FuelEfficiency PowerRating
## Merc 450SL 17.3 Bad 3
## Fiat 128 32.4 Good 2
## Ferrari Dino 19.7 Bad 1
#takes into account the appropriate order
v_cars <- c("Ferrari Dino","Fiat 128","Merc 450SL")
print(v_cars)
## [1] "Ferrari Dino" "Fiat 128" "Merc 450SL"
#Length of each car name
nchar(v_cars)
## [1] 12 8 10
#Creating a 3x3 Matrix
m_cars <- matrix(0, nrow = 3, ncol = 3)
rownames(m_cars) <- v_cars
colnames(m_cars) <- v_cars
print(m_cars)
## Ferrari Dino Fiat 128 Merc 450SL
## Ferrari Dino 0 0 0
## Fiat 128 0 0 0
## Merc 450SL 0 0 0
for(i in 1:nrow(m_cars)){
for(j in 1:ncol(m_cars)){
car_name_i = rownames(m_cars)[i]
car_name_j = colnames(m_cars)[j]
if(nchar(car_name_i) > nchar(car_name_j)){
m_cars[i,j] <- "Longer"
}else if(nchar(car_name_i) < nchar(car_name_j)){
m_cars[i,j] <- "Shorter"
}else {
m_cars[i,j] <- "Same"
}
}
}
print(m_cars)
## Ferrari Dino Fiat 128 Merc 450SL
## Ferrari Dino "Same" "Longer" "Longer"
## Fiat 128 "Shorter" "Same" "Shorter"
## Merc 450SL "Shorter" "Longer" "Same"
###Bonus convert matrix to data frame and rename ### Note: Accounting for renaming rows / columns in previous steps
#Converted to a data frame
m_cars_df = as.data.frame(m_cars)
m_cars_df
## Ferrari Dino Fiat 128 Merc 450SL
## Ferrari Dino Same Longer Longer
## Fiat 128 Shorter Same Shorter
## Merc 450SL Shorter Longer Same