Home > OS >  Apply gtExtras::gt_sparkline to multiple columns
Apply gtExtras::gt_sparkline to multiple columns

Time:10-19

Based on example code for sparkline from 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))

CodePudding user response:

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

  • Related