rdplyrpurrrgtgtextras

gtExtras::gt_sparkline to plot multiple columns with NAs without using na.omit()


Based on question from this this link:

df1 <- structure(list(type = c("v1", "v2"), `2017-06` = c(300, 100
), `2017-07` = c(10, 900), `2017-08` = c(500, 700
), `2017-09` = c(100, 650), `2017-10` = c(850, 600
)), class = "data.frame", row.names = c(NA, -2L))

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

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

df1 %>%
   transmute(type, data = pmap(across(-type), list)) %>%
   gt() %>%
   gt_sparkline(data)

I'm able to generate two plots:

enter image description here

After I modify data to df2 by adding NAs then using plot code above, none of them works and generates errors Error in if (med_y_rnd > 0) { : missing value where TRUE/FALSE needed:

df2 <- structure(list(type = c("v1", "v2"), `2017-06` = c(300, 100
), `2017-07` = c(10, 900), `2017-08` = c(500, NA
), `2017-09` = c(NA, 650), `2017-10` = c(850, 600
)), class = "data.frame", row.names = c(NA, -2L))

Please note I don't hope to remove NAs by using na.omit().

How could I deal with this issue? Any helps will be appreciated.

Reference link and code:

Reference code which may be helpful from the link in the end:

input_data <- 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") %>%
  dplyr::mutate(
    mpg_data = list(mpg_data[[1]], list(NA), list(NULL))
  )

input_data %>% 
  gt() %>% 
  gt_sparkline(mpg_data)

Out:

enter image description here

https://github.com/jthomasmock/gtExtras/issues/13


Solution

  • Thanks to the help from issue of gtExtras:

    library(tidyverse)
    library(gt)
    library(gtExtras)
    
    df <- structure(
      list(
        type = c("v1", "v2"),
        `2017-06` = c(300, 100),
        `2017-07` = c(10, 900), `2017-08` = c(500, NA), `2017-09` = c(NA, 650), `2017-10` = c(850, 600)
      ),
      class = "data.frame", row.names = c(NA, -2L)
    )
    
    df_list <- df %>%
      rowwise() %>%
      mutate(data = list(c_across(-type))) %>%
      select(type, data) %>% 
      ungroup() 
    
    df_list %>% 
     # remove the NA values from the vectors.
      mutate(data = purrr::map(data, ~.x[!is.na(.x)])) %>%
      gt() %>%
      gt_sparkline(data) %>% 
      gtsave("test.png")
    

    Output:

    enter image description here

    Reference link:

    https://github.com/jthomasmock/gtExtras/issues/33#issuecomment-996890443