我的R代码生成一些html输出,我想做两个非常简单的“查找和替换”类型调整:
R2,我想用R<sup>2</sup>替换[number] ***的整数在html中,我想用[number]<sup>***</sup>替换,即删除空格并添加上标。我一直想用str_replace_all()来做这件事。如果我能在潮间带里解决我的问题,那就太好了。
对于一个可重复的例子,我将使用mtcars从huxtable::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>")发布于 2020-06-09 04:00:29
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在下面的评论中提到的那样,您可以使用ϕ来避免阅读:
huxreg(fit1) %>%
to_html() %>%
str_replace_all(pattern = "R2", replacement = "R<sup>2</sup>") %>%
str_replace_all(pattern = fixed(" ***"), replacement = "<sup>***</sup>") %>%
writeLines(filepath)不过,最好不要用regex解析HTML。查看了红背心和xml2,以获得更健壮的工具。
发布于 2020-06-11 07:14:20
让我们保持简单:
h <- huxreg(fit1)
h[7, 1] <- "R<sup>2</sup>"
escape_contents(h)[7, 1] <- FALSE
h <- map_contents(h, by_regex("***" = "<sup>***</sup>",
.grepl_args = list(fixed = TRUE)))
h <- map_escape_contents(h, by_regex("***" = FALSE,
.grepl_args=list(fixed = TRUE)))
quick_html(h)https://stackoverflow.com/questions/62274646
复制相似问题