简体   繁体   中英

Huxtable in R give wrong formatting when using by_cases()

When I run this

library(tidyverse)

df = data.frame(
  stringsAsFactors = FALSE,
              Type = c("a", "b", "c", "d"),
                 A = c(51, 5, 10, 155.5),
                 P1 = c(40.1, 50.5, 127.8, 216),
                 C = c(40, 45, 50, 255)
     )

library(huxtable)
ht = as_hux(df)
ht %>% map_text_color( row = 2:nrow(df), col = 2:3,
                    by_cases(. < 50 ~ "red")) %>%
  set_all_borders()
ht

I get table: table

The problem is that 127.8 is bigger than 50 so it shouldn't be red. How to make it to be as I want?

The underlying issue is that adding cases has turned your numbers to character() . A workaround is to use by_cases(as.numeric(.) < 50 ~ "red") . Alternatively, write:

ht = as_hux(df, add_colnames = FALSE)
ht %>% map_text_color(col = 2:3,
                    by_cases(. < 50 ~ "red")) %>%
  add_colnames() %>%
  set_all_borders() %>%

which keeps the data as numeric until after you've done the colour mapping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM