`str_replace_all()在html输出上(来自huxtable())

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

我的R代码生成一些html输出,我想对以下两个类型进行非常简单的“查找和替换”类型调整:

  • 而不是html中的R2,我想替换为R<sup>2</sup>
  • html中[number] ***的中间部分,我想替换为[number]<sup>***</sup>,即删除空格并添加上标。

我一直在尝试用str_replace_all()来做到这一点。如果我能在tidyverse中解决我的问题,那就太好了。

对于一个可复制的示例,我将使用mtcarshuxtable::huxreg()生成html,这与在我的实际问题中生成输出的功能相同。

library(huxtable)
library(tidytext)

fit1 <- lm(mpg ~ disp, data = mtcars)

huxreg(fit1) %>% 
  quick_html()

给出的输出是此版本的html版本:

─────────────────────────────────────────────────
                                   (1)           
                        ─────────────────────────
  (Intercept)                        29.600 ***  
                                     (1.230)     
  disp                               -0.041 ***  
                                     (0.005)     
                        ─────────────────────────
  N                                  32          
  R2                                  0.718      
  logLik                            -82.105      
  AIC                               170.209      
─────────────────────────────────────────────────
  *** p < 0.001; ** p < 0.01; * p < 0.05.        

Column names: names, model1

所以我尝试在str_replace_all()R2上使用***,但是我的输出似乎保持不变。我可以通过简单的方法进行替换吗?

huxreg(fit1) %>% 
  quick_html() %>% 
  str_replace_all(pattern = "R2", replacement = "R<sup>2</sup>") %>% 
  str_replace_all(pattern = " ***", replacement = "<sup>***</sup>")
r regex tidyverse stringr tidytext
1个回答
2
投票

quick_html()返回NULL,而不是它生成的HTML文本,然后将其保存到文件中(默认为huxtable-output.html)。您可以重新读取该文件并对其运行regex:

library(huxtable)
library(stringr)

fit1 <- lm(mpg ~ disp, data = mtcars)
filepath <- 'huxtable-output.html'

huxreg(fit1) %>% 
    quick_html(file = filepath, open = FALSE)

readLines(filepath) %>% 
    str_replace_all(pattern = "R2", replacement = "R<sup>2</sup>") %>% 
    str_replace_all(pattern = fixed(" ***"), replacement = "<sup>***</sup>") %>% 
    writeLines(filepath)

# open file in browser
browseURL(filepath)

或者如下面的评论中的@ 27ϕ9所述,您可以使用huxtable::to_html()避免读回:

huxreg(fit1) %>% 
    to_html() %>%
    str_replace_all(pattern = "R2", replacement = "R<sup>2</sup>") %>% 
    str_replace_all(pattern = fixed(" ***"), replacement = "<sup>***</sup>") %>% 
    writeLines(filepath)

[Maybe better not to parse HTML with regex, though.签出rvestxml2,以获得为此目的而设计的更强大的工具。

© www.soinside.com 2019 - 2024. All rights reserved.