代码之家  ›  专栏  ›  技术社区  ›  Bloxx

格式化,将NA更改为“-”,并将值保持为数字

  •  0
  • Bloxx  · 技术社区  · 3 年前

    我正试着做一张漂亮的桌子 formattable 我闪亮的应用程序。我想将单元格范围和NA的阴影作为 - 。

    example <- structure(list(`2022` = c(NA_integer_, NA_integer_, NA_integer_, 
    NA_integer_, NA_integer_, NA_integer_), `2021` = c(929L, NA, 
    165L, 265L, 5616L, 13L), `2020` = c(660L, NA, 98L, 266L, 6735L, 
    15L), `2019` = c(598L, NA, 96L, 326L, 6236L, 14L), `2018` = c(479L, 
    NA, 107L, 384L, 4486L, 14L), `2017` = c(NA, NA, -547L, -3548L, 
    3895L, 20L), `2016` = c(NA, NA, 19L, 535L, 6345L, 24L)), row.names = c(NA, 
    -6L), class = c("tbl_df", "tbl", "data.frame"))
    
    formattable(example,
                list(` ` = formatter("span", style = ~ style(color = "black",font.weight = "bold")),
                     area(col = 1:7) ~ color_tile("#DeF7E9", "#71CA97")))
    
    

    我的问题是:是否可以将NA作为字符,并且仍然使用基于数值的着色?

    1 回复  |  直到 3 年前
        1
  •  1
  •   nd37255    3 年前

    这能产生你想要的东西吗?

    library(formattable)
    library(dplyr)
    library(tidyr)
    
    example <- structure(list(`2022` = c(
      NA_integer_, NA_integer_, NA_integer_,
      NA_integer_, NA_integer_, NA_integer_
    ), `2021` = c(
      929L, NA,
      165L, 265L, 5616L, 13L
    ), `2020` = c(
      660L, NA, 98L, 266L, 6735L,
      15L
    ), `2019` = c(598L, NA, 96L, 326L, 6236L, 14L), `2018` = c(
      479L,
      NA, 107L, 384L, 4486L, 14L
    ), `2017` = c(
      NA, NA, -547L, -3548L,
      3895L, 20L
    ), `2016` = c(NA, NA, 19L, 535L, 6345L, 24L)), row.names = c(
      NA,
      -6L
    ), class = c("tbl_df", "tbl", "data.frame"))
    
    example |>
      dplyr::mutate_all(.funs = ~ tidyr::replace_na(as.character(.x), "-")) |>
      formattable(
        list(
          ` ` = formatter("span", style = ~ style(color = "black", font.weight = "bold")),
          area(col = 1:7) ~ color_tile("#DeF7E9", "#71CA97")
        )
      )
    #> Warning in gradient(as.numeric(x), ...): NAs introduced by coercion
    

    创建于2022-11-16 reprex v2.0.2

    enter image description here

    如果要将NA值替换为“-”,则必须转换为字符列。然后,函数“replace_na”将na替换为指定值。这可能会打乱其他一些事情,但看起来formattable仍然会通过转换为整数来对其进行样式设置。

    推荐文章