Reputation: 10011
For the following df
, if none of type
with all NA
or NA_real_
, the following code works:
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)
Out:
If I change v3
with all NA
s and rerun the rest of code:
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)
)
I will get an error:
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
How could deal with this exception by drawing no sparkline if one variable with all NA
s for each month? Thanks.
Note: I try to make sparklines were drawn when one variable has at least 2 not NA
s values by setting purrr::map(data, ~.x[!is.na(.x) & length(.x) >=2])
, but it not working, since v3
was drawn with one point, but it only has one effective value, which is 5. How could I do that correctly?
Upvotes: 1
Views: 135
Reputation: 124048
One option would be to adjust your mutate/map
using an if
condition to return a scaler NA
for cases where there are only missing values or only one non-missing value:
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)
Upvotes: 1