jthomasmock / gtExtras

A Collection of Helper Functions for the gt Package.
https://jthomasmock.github.io/gtExtras/
Other
193 stars 26 forks source link

Error in if (med_y_rnd > 0) { : missing value where TRUE/FALSE needed #33

Closed ahbon123 closed 2 years ago

ahbon123 commented 2 years ago

I'm trying to plot sparkline with NAs rows:

library(dplyr)
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 %>%
  rowwise() %>%
  mutate(data = list(c_across(-type))) %>%
  select(type, data) %>%
  gt() %>%
  gt_sparkline(data)

or:

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

Out:

Error in if (med_y_rnd > 0) { : missing value where TRUE/FALSE needed How could I deal with this issue? Any helps will be appreciated.

jthomasmock commented 2 years ago

Howdy! You can avoid using NA values since they won't be graphed. Note the exclusion of NAs from the list vectors in the mutate(data = purrr::map(data, ~.x[!is.na(.x)])) step .

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
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")

Created on 2021-12-17 by the reprex package (v2.0.1)