# Loading libraries
library(dplyr)
library(dslabs)
library(ggplot2)w3-2
data(heights)
tall_males <- heights$sex == "Male" & heights$height > 70
#summarise allows us to get summaty data - summaty statistics like mean, sd
s <- heights %>% filter(sex == "Female") %>% summarise(average = mean(height), standard_deviation = sd(height))# Output
s$average[1] 64.93942
s$standard_deviation[1] 3.760656
# group_by(sex) tells R to treat the dataset as two separate groups — M and F
height_grp <- heights %>% group_by(sex)
height_grp %>% summarize (avg = mean(height), stdev = sd(height))# A tibble: 2 × 3
sex avg stdev
<fct> <dbl> <dbl>
1 Female 64.9 3.76
2 Male 69.3 3.61
# Arrange Function
#arrange() allows us to order entire tables.
data("murders")
murders %>% arrange(population) %>% head() #order by population state abb region population total
1 Wyoming WY West 563626 5
2 District of Columbia DC South 601723 99
3 Vermont VT Northeast 625741 2
4 North Dakota ND North Central 672591 4
5 Alaska AK West 710231 19
6 South Dakota SD North Central 814180 8
#desc() allows us to sort in descending order
data("murders")
murders %>% arrange(desc(total)) %>% head() #order by descending rate state abb region population total
1 California CA West 37253956 1257
2 Texas TX South 25145561 805
3 Florida FL South 19687653 669
4 New York NY Northeast 19378102 517
5 Pennsylvania PA Northeast 12702379 457
6 Michigan MI North Central 9883640 413
table(heights$sex)
Female Male
238 812
# Plotting
heights %>% ggplot(aes(sex, fill=sex)) + geom_bar() heights %>% count(sex) %>% mutate(proportion = n/sum(n)) #gives us the proportion sex n proportion
1 Female 238 0.2266667
2 Male 812 0.7733333
#Add your own color choices for the different bars
#data(murders)
murders %>% ggplot(aes(region, fill= region)) + geom_bar() + scale_fill_manual(values=c("#FF0000", "#FFFFFF", "#D3D3D3", "#A9A9A9")) #red, white, lightgray, darkgray# Boxplot
heights %>% ggplot(aes(sex,height,fill=sex)) + geom_boxplot() +scale_fill_manual(values=c("white","red")) murders %>% ggplot(aes(region,total, fill= region)) + geom_boxplot() + scale_fill_manual(values=c("red", "white", "lightgray", "darkgray"))