This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
# Wrangling the Gapminder dataset for the year 2007
gapminder_2007 <- gapminder %>%
filter(year == 2007) %>%
select(country, continent, lifeExp, gdpPercap, pop) %>%
mutate(
gdp_million = gdpPercap * pop / 1e6
)
# Display a snapshot of the wrangled data
head(gapminder_2007)
## # A tibble: 6 × 6
## country continent lifeExp gdpPercap pop gdp_million
## <fct> <fct> <dbl> <dbl> <int> <dbl>
## 1 Afghanistan Asia 43.8 975. 31889923 31079.
## 2 Albania Europe 76.4 5937. 3600523 21376.
## 3 Algeria Africa 72.3 6223. 33333216 207445.
## 4 Angola Africa 42.7 4797. 12420476 59584.
## 5 Argentina Americas 75.3 12779. 40301927 515034.
## 6 Australia Oceania 81.2 34435. 20434176 703658.
# Generate summary statistics for each continent
summary_table <- gapminder_2007 %>%
group_by(continent) %>%
summarise(
avg_lifeExp = mean(lifeExp),
total_population = sum(pop),
total_gdp_million = sum(gdp_million)
) %>%
arrange(desc(total_population))
# Display the table
kable(summary_table, caption = "Summary Statistics by Continent")
continent | avg_lifeExp | total_population | total_gdp_million |
---|---|---|---|
Asia | 70.72848 | 3811953827 | 20707950.0 |
Africa | 54.80604 | 929539692 | 2380485.7 |
Americas | 73.60812 | 898871184 | 19418085.7 |
Europe | 77.64860 | 586098529 | 14795499.3 |
Oceania | 80.71950 | 24549947 | 807314.1 |
You can also embed plots, for example:
ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp, color = continent)) +
geom_point(size = 3, alpha = 0.7) +
scale_x_log10() +
labs(
title = "Life Expectancy vs GDP per Capita (2007)",
x = "GDP per Capita (log scale)",
y = "Life Expectancy"
) +
theme_minimal()
# Generate random sample coordinates for the map
gapminder_2007_map <- gapminder_2007 %>%
mutate(
long = runif(n(), min = -180, max = 180),
lat = runif(n(), min = -90, max = 90)
)
# Create the map
leaflet(gapminder_2007_map) %>%
addTiles() %>%
addCircleMarkers(
~long, ~lat,
color = ~ifelse(lifeExp > 70, "green", "red"),
radius = ~sqrt(pop) / 10000,
popup = ~paste0(
"<b>Country:</b> ", country, "<br>",
"<b>Life Expectancy:</b> ", lifeExp, "<br>",
"<b>GDP:</b> $", round(gdpPercap, 2)
)
)
Note that the echo = FALSE
parameter was added to the
code chunk to prevent printing of the R code that generated the
plot.