为什么kableExtra cell_spec在条件格式化期间丢失尾随的十进制零?

问题描述 投票:2回答:1

我喜欢有两个小数,通常在kable上可以正常工作。但是,如果有一个条件为TRUE的单元格,则将kableExtra用于条件格式设置不会显示尾随零。

[MWE显示了一种情况,如果该值大于1.2,则得到一个粗体单元格,而由于没有值大于1.5,而没有粗体单元的情况。条件格式按预期工作。但是在4个示例中的3个中,我丢失了结尾的零。

非常欢迎任何关于为什么(以及如何防止这种影响的想法。)>

# MWE kableExtra cell_spec loses trailing decimal zeros during conditional formatting

rm(list=ls())
library("knitr")
library("kableExtra") 
library("dplyr")


df <- data.frame(item=c(1 , 1.2, 1.23))

# Condition for cell-specification for each cell false
df[df$item>1.5,1] <- cell_spec (df[df$item>1.5,1], "html",bold=TRUE)

# output for each cell with two decimals
knitr::kable(df, digits=2,  escape=FALSE)

item

1.00

1.20

1.23

df <- data.frame(item=c(1 , 1.2, 1.23))
# Condition for cell-specification for one cell true
df[df$item>1.2,1] <- cell_spec (df[df$item>1.2,1], "html",bold=TRUE)

# output for each cell with needed decimals only, trailing zeros lost
knitr::kable(df, digits=2, escape=FALSE)

item

1

1.2

1.23

df <- data.frame(item=c(1 , 1.2, 1.23))
# alternative way loses trailing zeros whether condition is TRUE or FALSE 
df %>%
  transmute(cell_spec(df$item, bold=ifelse(df$item>1.5,"TRUE","FALSE"))) %>%
  kable( digits=2, escape=FALSE)

cell_spec(dfitem,bold = ifelse(dfitem> 1.5,“ TRUE”,“ FALSE”))]]] >>

1

1.2

1.23

df <- data.frame(item=c(1 , 1.2, 1.23))
df %>%
  transmute(cell_spec(df$item, bold=ifelse(df$item>1.2,"TRUE","FALSE"))) %>%
  kable( digits=2, escape=FALSE)

cell_spec(dfitem,bold = ifelse(dfitem> 1.5,“ TRUE”,“ FALSE”))]]] >>

1

1.2

1.23

我喜欢有两个小数,通常在kable上可以正常工作。但是,如果有一个条件为TRUE的单元格,则将kableExtra用于条件格式设置不会显示尾随零。 ...

之所以会出现这种效果,是因为cell_spec项转换为字符后。在cell_spec完成之前,创建另一列并转换为尾随零的字符。

但是,cell_spec的条件遵循原始值。

df <- data.frame(item=c(1 , 1.2, 1.23))


df$itemCharacter <- as.character(formatC(df$item, digits = 2, format = 'f')) #new character variable with format specification

df[df$item>1.2,2] <- cell_spec (df[df$item>1.2,2], "html",bold=TRUE) #condition for cell_spec with the old variable, but assigned to the new variable

knitr::kable(df$itemCharacter, digits=2,  escape=FALSE) #output of the new variable

x

1.00

1.20

1.23

r conditional-formatting kableextra trailing
1个回答
0
投票

之所以会出现这种效果,是因为cell_spec项转换为字符后。在cell_spec完成之前,创建另一列并转换为尾随零的字符。

但是,cell_spec的条件遵循原始值。

df <- data.frame(item=c(1 , 1.2, 1.23))


df$itemCharacter <- as.character(formatC(df$item, digits = 2, format = 'f')) #new character variable with format specification

df[df$item>1.2,2] <- cell_spec (df[df$item>1.2,2], "html",bold=TRUE) #condition for cell_spec with the old variable, but assigned to the new variable

knitr::kable(df$itemCharacter, digits=2,  escape=FALSE) #output of the new variable
© www.soinside.com 2019 - 2024. All rights reserved.