R: formattable's style parameters' content displayed on output picture

161 views Asked by At

Given a dataframe as follows:

df <- structure(list(` ` = c("v1", "v2", "v3", "v4", "v5", "v5", "v6", "v7", "v8", 
                       "v9", "v10"), last_week = c(10, 31.34, 85.86, 
3375.01, 7721.54, 9, 18.28, 58.84, 6177.73, 19890.55, 36.35), 
    this_week = c(27, 47.25, 99.4, 2253.04, 4861.4, 20, 43.04, 52.89, 
    2395.22, 2943.64, 12.67), pct = structure(c(1.7, 0.5077, 
    0.1577, -0.3324, -0.3704, 1.2222, 1.3545, -0.1011, -0.6123, 
    -0.852, -0.6515), formattable = list(formatter = "formatC", 
        format = list(format = "f", digits = 2L), preproc = "percent_preproc", 
        postproc = "percent_postproc"), class = c("formattable", 
    "numeric"))), class = "data.frame", row.names = c(NA, -11L
))

I try to use 0.2.1 version of formattable package to create a stylish table:

library(formattable)
formattable(df,
            list(
              ~formatter("span",
                        style = x ~ formattable::style(display = "block",
                                                       "border-radius" = "2px",
                                                       "padding" = "2px",
                                                       "text-align" = "left")
                        ),
              last_week = color_tile("#DeF7E9", "#FA614B"),
              this_week = color_tile("#DeF7E9", "#FA614B"),
              `pct` = formatter("span",
                 style = ~ style(color = ifelse(`this_week` > `last_week`, "red", "green")),
                 ~ icontext(sapply(`pct`, function(x) if (x < 0) "arrow-down" else if (x > 0) "arrow-up" else ""), `pct`)))
)

Out:

enter image description here

But as you can see, the this_week and last_week columns are not regular numbers.

It has worked out before, but it seems error raised after I updated packages.

Anyone knows how can I deal with this issue? Thanks.

1

There are 1 answers

1
Basti On BEST ANSWER

I managed to solve your problem by changing formatter parameter changing ~ by df= :

formattable(df,
            list(
              df=formatter("span",
                         style = x ~ formattable::style(display = "block",
                                                        "border-radius" = "2px",
                                                        "padding" = "2px",
                                                        "text-align" = "left")
              ),
              last_week = color_tile("#DeF7E9", "#FA614B"),
              this_week = color_tile("#DeF7E9", "#FA614B"),
              `pct` = formatter("span",
                                style = ~ style(color = ifelse(`this_week` > `last_week`, "red", "green")),
                                ~ icontext(sapply(`pct`, function(x) if (x < 0) "arrow-down" else if (x > 0) "arrow-up" else ""), `pct`)))
)