library(dslabs)
library(tidyverse)
library(ggplot2)
library(dplyr)Week 3
Week 3
data(heights)
str(heights)'data.frame': 1050 obs. of 2 variables:
$ sex : Factor w/ 2 levels "Female","Male": 2 2 2 2 2 1 1 1 1 2 ...
$ height: num 75 70 68 74 61 65 66 62 66 67 ...
head(heights) sex height
1 Male 75
2 Male 70
3 Male 68
4 Male 74
5 Male 61
6 Female 65
Finding people who are male AND taller than 70 inches
tall_males <- heights$sex == "Male" & heights$height > 70
summary(tall_males) Mode FALSE TRUE
logical 744 306
Taking the average height and standard deviation of female.
s <- heights |>
filter(sex=="Female") |>
summarize(Average = mean(height), Standard_deviation = sd(height))
s Average Standard_deviation
1 64.93942 3.760656
Taking out mean and sd ofo both sex at once by grouping
height_grp <- heights |>
group_by(sex)
height_grp |>
summarise(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
height_grp# A tibble: 1,050 × 2
# Groups: sex [2]
sex height
<fct> <dbl>
1 Male 75
2 Male 70
3 Male 68
4 Male 74
5 Male 61
6 Female 65
7 Female 66
8 Female 62
9 Female 66
10 Male 67
# ℹ 1,040 more rows
Arranging the data according to the population, lowest the first.
murders |>
arrange(population) |>
head() 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
Arranging the data according to the population, Larger to small
murders |>
arrange(desc(population)) |>
head() 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 Illinois IL North Central 12830632 364
6 Pennsylvania PA Northeast 12702379 457
# Table and summary
table(heights$sex)
Female Male
238 812
summary(heights$sex)Female Male
238 812
table(murders$region)
Northeast South North Central West
9 17 12 13
summary(murders$region) Northeast South North Central West
9 17 12 13
Creating a ggplot of male and female “sex”.
ggplot(heights) +
aes(sex, fill = sex) +
geom_bar()Counting and mutate and finding proportion.
heights |>
count(sex) |>
mutate(proportion = n/sum(n)) sex n proportion
1 Female 238 0.2266667
2 Male 812 0.7733333
Adding color to the boxplot by own choice.
ggplot(murders) +
aes(region, fill = region) +
geom_bar() +
scale_fill_manual(values = c("blue", "white", "green", "red"))Creating a boxplot and manually adding own colors.
ggplot(heights) +
aes(sex, height, fill = sex) +
geom_boxplot() +
scale_fill_manual(values = c("white", "red"))