1

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))
ah bon
  • 9,293
  • 12
  • 65
  • 148

2 Answers2

1

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

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks but why it's straight line without fluctuation? With my edit code, it generates same result. – ah bon Oct 18 '21 at 06:26
  • 1
    Because there isn't any fluctuation in the data ? They are very close to each other. If you change the value `df$\`2017-08\` <- 100` then you'll see fluctuations. I think it is completely dependent on the data that you have. – Ronak Shah Oct 18 '21 at 06:31
  • I have edited data by adding one more column `value` which I don't want it shown in the graph but keep it as column in output, how could i do that? which means the output will have one column `value` to the current one, others are all same. – ah bon Oct 18 '21 at 08:36
  • 1
    @ahbon `df %>% rowwise() %>% mutate(data = list(c_across(matches('^\\d+')))) %>% select(type, value, data) %>%gt() %>%gt_sparkline(data)` – Ronak Shah Oct 18 '21 at 10:30
1

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

ah bon
  • 9,293
  • 12
  • 65
  • 148
akrun
  • 874,273
  • 37
  • 540
  • 662