Insert a code block and then answer each question below. If your code returns something less than a specific answer (e.g. if the question asks for a country but your code returns a table), then include a sentence or two below that gives a precise answer to the question.
library(tidyverse)
## Warning: package 'ggplot2' was built under R version 4.4.3
## Warning: package 'tibble' was built under R version 4.4.3
## Warning: package 'tidyr' was built under R version 4.4.3
## Warning: package 'readr' was built under R version 4.4.3
## Warning: package 'purrr' was built under R version 4.4.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.4 ✔ readr 2.1.6
## ✔ forcats 1.0.1 ✔ stringr 1.6.0
## ✔ ggplot2 4.0.1 ✔ tibble 3.3.1
## ✔ lubridate 1.9.4 ✔ tidyr 1.3.2
## ✔ purrr 1.2.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(gapminder)
gapminder
gapminder %>%
filter(year == 1952) %>%
filter(continent == "Asia") %>%
arrange(lifeExp)
Afghanistan had the lowest life expectancy of the Asian countries in 1952.
mutate() function, make a new variable that
is 1 if life expectancy is higher than 60 and 0 otherwise. Save the
results into a new tibble.gapminder %>%
mutate(life60 = lifeExp > 60) %>%
mutate(life60 = life60 * 1)
gapminder %>%
filter(year == 1992) %>%
summarise(total_countries = n(), countries_above_60 = sum(lifeExp > 60),fraction = countries_above_60 / total_countries)
group_by() more than one variable at a time. Save the
results into a new tibble.lifeover60 <- gapminder %>%
group_by(continent, year) %>%
summarise(total_countries = n(), countries_above_60 = sum(lifeExp > 60),fraction = countries_above_60 / total_countries)
## `summarise()` has grouped output by 'continent'. You can override using the
## `.groups` argument.
ggplot(), make a line plot that shows fraction of countries
with a life expectancy over 60 in each continent over time. Try to make
the graph look good (proper axis labels, perhaps a different
theme).lifeover60 %>%
ggplot(aes(x = year, y = countries_above_60, colour = continent, size = countries_above_60)) +
geom_point()+
labs(x = "Years", y = "# of Countries With LifeExp > 60" )