gtExtras::gt_sparkline 在不使用 na.omit() 的情况下用 NA 绘制多列

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

基于这个

的问题
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)

我可以生成两个图:

在我通过添加 NAs 然后使用上面的绘图代码将数据修改为 df2 之后,其中 none 工作并产生错误 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))

请注意我不希望使用na.omit()删除NA。

我该如何处理这个问题?任何帮助将不胜感激。

参考link及代码:

最后link可能有帮助的参考代码:

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)

输出:

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

感谢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")

输出:

引用link:

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