built by R htmlwidgets
sparkline
... assembled with blockbuilder.org
Motivated by CRAN submission of sparkline
with some new helper functions, I set out to apply on some real live data. I chose US Treasury yields from the H15 series on Fred. quantmod + dplyr + purrr + formattable + sparkline made this incredibly easy.
library(quantmod)
library(purrr)
library(dplyr)
library(tibble)
library(pipeR)
library(sparkline)
library(formattable)
bond_tbl <- function(bond){
getSymbols(
paste0("DGS", bond),
src="FRED",
auto.assign=FALSE
)
}
yields <- c(5,10,30) %>>%
map(bond_tbl) %>>%
{do.call(merge.xts,.)}
# get a universal max for our sparklines
yield_max <- max(yields, na.rm = TRUE)
# define sparkline helper to remove NA
spk_nonull <- function(x, ...){
x <- na.omit(x)
spk_chr(values = x, ...)
}
(tbl_box <- yields %>>%
as.data.frame(stringsAsFactors = FALSE) %>>%
as_tibble() %>>%
rownames_to_column(var = "Date") %>>%
mutate(Decade = paste0(substr(Date,1,3),"0")) %>>%
group_by(Decade) %>%
select(-Date) %>>%
summarise_all(
spk_nonull, chartRangeMin = 0, chartRangeMax = yield_max, type = "box"
) %>>%
formattable( caption = tags$h3("US Bond Yields by Decade") ) %>>%
as.htmlwidget() %>>%
spk_add_deps()
)
(tbl_line <- yields %>>%
as.data.frame(stringsAsFactors = FALSE) %>>%
as_tibble() %>>%
rownames_to_column(var = "Date") %>>%
mutate(Decade = paste0(substr(Date,1,3),"0")) %>>%
group_by(Decade) %>%
select(-Date) %>>%
summarise_all(
spk_chr, chartRangeMin = 0, chartRangeMax = yield_max, type = "line"
) %>>%
formattable( caption = tags$h3("US Bond Yields by Decade") ) %>>%
as.htmlwidget() %>>%
spk_add_deps()
)
browsable(
tagList(
tbl_box,
tbl_line
)
)