1

对于以下df,如果没有typeallNANA_real_,则以下代码有效:

library(gt)
library(gtExtras)

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

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) & length(.x) >=2])) %>%
  gt() %>%
  gt_sparkline(data) 

出去:

在此处输入图像描述

如果我更改v3所有NAs 并重新运行其余代码:

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

我会收到一个错误:

Error: Tibble columns must have compatible sizes.
* Size 2: Existing data.
* Size 0: Column `y`.
i Only values of size one are recycled.
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning messages:
1: In max(vals, na.rm = TRUE) :
  no non-missing arguments to max; returning -Inf
2: In min(vals, na.rm = TRUE) :
  no non-missing arguments to min; returning Inf

NA如果每个月的一个变量都为 s,如何通过不绘制迷你图来处理此异常?谢谢。

NA注意:当一个变量通过设置至少有 2 个 not s 值时,我尝试绘制迷你图purrr::map(data, ~.x[!is.na(.x) & length(.x) >=2]),但它不起作用,因为它v3是用一个点绘制的,但它只有一个有效值,即 5。我该怎么做对吗?

4

1 回答 1

1

一种选择是调整您的mutate/map使用条件以在只有缺失值或只有一个非缺失值的情况下if返回缩放器:NA

df_list %>% 
  # remove the NA values from the vectors.
  mutate(data = purrr::map(data, function(.x) {
    .x <- .x[!is.na(.x)]; if (length(.x) < 2) NA_real_ else .x
  })) %>%
  gt() %>%
  gt_sparkline(data) 

在此处输入图像描述

于 2022-01-26T11:16:53.753 回答