by Andrie de Vries
Sparklines is a useful tool for visualizing time series data using small inline plots. In this post I demonstrate how to create sparklines in tables, using the gapminder data.
The code
Load the required packages
library(tidyverse)
## -- Attaching packages ----------------------------------------------------------- tidyverse 1.2.1 --
## v ggplot2 2.2.1 v purrr 0.2.4
## v tibble 1.4.2 v dplyr 0.7.4
## v tidyr 0.8.0 v stringr 1.3.0
## v readr 1.1.1 v forcats 0.3.0
## -- Conflicts -------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(gapminder)
library(sparkline)
library(formattable)
library(DT)
Some helper functions to round numbers and get the last element of a vector
round_0 <- function(x) round(x, digits = 0)
round_1 <- function(x) round(x, digits = 1)
last_round_1 <- function(x) dplyr::last(x) %>% round_1()
last_round_0 <- function(x) dplyr::last(x) %>% round_0()
Compute the summaries
gapminder %>%
filter(continent == "Africa") %>%
group_by(country) %>%
summarise(
`life expectancy` = spk_chr(round_1(lifeExp)),
`life expectancy (years)` = last_round_1(lifeExp),
`gdp per capita` = spk_chr(gdpPercap %>% round_0()),
`gdp per capita (USD)` = last_round_0(gdpPercap),
`population (M)` = last_round_1(pop / 1e6)
) %>%
formattable() %>%
as.datatable() %>%
spk_add_deps()
You may leave a comment below or discuss the post in the forum community.rstudio.com.