Apply gtExtras::gt_sparkline to multiple columns

419 views Asked by At

Based on example code for sparkline from this link:

library(gt)
library(gtExtras)
mtcars %>%
    dplyr::group_by(cyl) %>%
    # must end up with list of data for each row in the input dataframe
    dplyr::summarize(mpg_data = list(mpg), .groups = "drop") %>%
    gt() %>%
    gt_sparkline(mpg_data)

Out:

enter image description here

Now I hope to apply code above to the data df below, which means use type as cyl, other year-month columns as mpg-data:

structure(list(type = c("v1", "v2"), `2017-06` = c(244.955, 9e-04
), `2017-07` = c(244.786, -7e-04), `2017-08` = c(245.519, 0.003
), `2017-09` = c(246.819, 0.0053), `2017-10` = c(246.663, -6e-04
)), class = "data.frame", row.names = c(NA, -2L))

enter image description here

How could I achieve that? Thanks.

EDIT:

data <- melt(df, id = 'type')
data %>%
    dplyr::group_by(type) %>%
    # must end up with list of data for each row in the input dataframe
    dplyr::summarize(values = list(value), .groups = "drop") %>%
    gt() %>%
    gt_sparkline(values)

Out:

enter image description here

Edited data by adding value column:

structure(list(type = c("v1", "v2"), `2017-06` = c(244.955, 9e-04
), `2017-07` = c(244.786, -7e-04), `2017-08` = c(245.519, 0.003
), `2017-09` = c(246.819, 0.0053), `2017-10` = c(246.663, -6e-04
), value = c(1.2, 1.6)), class = "data.frame", row.names = c(NA, -2L))
2

There are 2 answers

4
Ronak Shah On BEST ANSWER

You may use rowwise and collapse all the data of the row in a list.

library(dplyr)
library(gt)
library(gtExtras)

df %>%
  rowwise() %>%
  mutate(data = list(c_across(-type))) %>%
  select(type, data) %>%
  gt() %>%
  gt_sparkline(data)

enter image description here

3
akrun On

We may use pmap from purrr

library(gt)
library(gtExtras)
library(dplyr)
library(purrr)
df %>%
   transmute(type, data = pmap(across(-type), list)) %>%
   gt() %>%
   gt_sparkline(data)

Output:

enter image description here