0

I want to create a table which show how data changed in past months. I've been trying to do it in gt package I couldn't understand why it doesn't work.

example data

df <- data.frame(
  group = c("x", "x", "y", "y", "z", "z"),
  sub_group = c("1", "2", "1", "2", "1", "2"),
  jan = c(1, 2, 3, 3, 4, 1),
  feb = c(2, 3, 1, 3, 2, 4),
  mar = c(9, 2, 5, 3, 1, 4)
)

I've tried gt_plt_sparkline function two different ways.

  1. First I added a column like it said in the wiki.
data %>%
  mutate(summary = list(data[1,3:5])) %>%
  gt() %>% 
  gt_plt_sparkline(column = 6)

this resulted where every sparkline is sparkline of first groupfirst try

  1. I've tried to manipulate it with row function
data %>%
  mutate(summary = list(data[row(data),3:5])) %>%
  gt() %>% 
  gt_plt_sparkline(column = 6)

but this throw the error Error in FUN(X[[i]], ...) : 'list' object cannot be coerced to type 'double'

Is there a way around this or should I change data structure?

1 Answer 1

1

Here is one option to create the desired list column for each sparkline using purrr::map_dbl:

library(gt)
library(gtExtras)
library(dplyr, warn = FALSE)
library(purrr)

df |>
  group_by(group, sub_group) |>
  mutate(
    col_spark = list(
      purrr::map_dbl(
        pick(everything()), \(x) matrix(x)[1, , drop = TRUE]
      )
    )
  ) %>%
  ungroup() |>
  gt() %>%
  gt_plt_sparkline(column = 6)

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.