2

基于此链接的问题:

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)

我能够生成两个图:

在此处输入图像描述

在我df2通过添加NAs 然后使用上面的绘图代码修改数据后,它们都不起作用并产生错误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().

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

参考链接和代码:

最后的链接中可能有帮助的参考代码:

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

4

1 回答 1

0

感谢问题的帮助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")

输出:

在此处输入图像描述

参考链接:

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

于 2021-12-18T02:20:38.013 回答