kableExtra生成表格时模型名含数字出现 的解决方法
解决modelsummary表格列标题出现
的问题 问题原因
当模型名称包含数字时,modelsummary生成HTML格式表格(kableExtra依赖HTML输出)时,会自动插入非断空格( )防止标题意外换行,最终导致列标题出现多余的 。
解决方法
以下几种方案可消除该问题:
手动指定模型名称
通过model.names参数直接定义列标题,绕过自动转义逻辑:library(modelsummary) library(tidyverse) library(kableExtra) models <- list( "Bivariate 1" = lm(mpg ~ cyl, mtcars), "Bivariate 2" = lm(mpg ~ cyl + drat, mtcars), "Multiple" = lm(hp ~ cyl + drat, mtcars) ) modelsummary(models, output = 'kableExtra', title = 'Table customized using `kableExtra` functions.', stars = TRUE, notes = c('First custom note to contain text.', 'Second custom note with different content.'), model.names = c("Bivariate 1", "Bivariate 2", "Multiple")) %>% add_header_above(c(" " = 1, "Miles / Gallon" = 2, "Horsepower" = 1))后处理替换非断空格
生成表格后,用gsub替换掉HTML中的 :modelsummary(models, output = 'kableExtra', title = 'Table customized using `kableExtra` functions.', stars = TRUE, notes = c('First custom note to contain text.', 'Second custom note with different content.')) %>% add_header_above(c(" " = 1, "Miles / Gallon" = 2, "Horsepower" = 1)) %>% gsub(pattern = " ", replacement = " ", x = .)关闭自动转义(谨慎使用)
使用escape = FALSE参数关闭HTML自动转义,但可能影响其他特殊字符的显示,需按需使用:modelsummary(models, output = 'kableExtra', title = 'Table customized using `kableExtra` functions.', stars = TRUE, notes = c('First custom note to contain text.', 'Second custom note with different content.'), escape = FALSE) %>% add_header_above(c(" " = 1, "Miles / Gallon" = 2, "Horsepower" = 1))
内容的提问来源于stack exchange,提问作者Florian Reiche
相关产品推荐
相关产品推荐

