attach(mtcars)
library(dplyr)
library(reshape2)
library(ggplot2)
mtcars.edit <- mtcars %>%
select(mpg, cyl, gear, carb) %>% ##Select chooses certain columns from your data
filter(mpg <= 30 & mpg >= 15) %>% ## Filter chooses certain values in ROWS of your data
group_by(cyl) ##Aggregates data by a certain column
##Now let's make a second data frame...
mtcars.edit2 <- mtcars %>%
select(cyl, wt, hp) %>%
group_by(cyl) %>%
mutate(carpower = wt/hp) ## nonsenical metric, but ok for our purposes
##Now, we can merge the two data sets
##Remember to know how both of your data sets are indexed, so that they can merge evenly
mtcars.total <- merge(mtcars.edit, mtcars.edit2, by.x = "cyl", by.y = "cyl")
###Now lets make some of these data long-forms, so that we can work with graphing them in a stacked bar chart
###For this we will need the melt function
mtcars.edit.long <- melt(mtcars.edit, id.vars = "mpg", variable.name = "Car_Stuff", value.name = "Values")
##Now let's make a stacked barplot using ggplot2
##A subsequent lecture will cover ggplot, but this module will work through the basic structure
cars.plot <- ggplot() +
geom_bar(data = mtcars.edit.long, aes(mpg , Values, fill = Car_Stuff), stat= "identity") +
ylab("Values") +
xlab("MPG") +
ggtitle("A Nonsenical Stacked Barplot") +
theme_bw()
cars.plot