gpt4 book ai didi

r - 来自 R 脚本的循环 tbl_regression 不为 rmarkdown::render 打印

转载 作者:行者123 更新时间:2023-12-05 05:56:25 25 4
gpt4 key购买 nike

我正在使用 .R 脚本进行分析,并使用 rmarkdown::render 打印到 word 文档。对于格式化输出,我使用 gtsummary 库,因为我想遍历多个变量,所以我在 for 循环中有模型。模型运行,但输出未打印到 word 文档 - 即使包含 results = 'asis' 选项。

脚本 1

library(gtsummary)  # formatted model output

#'# Example dataset
dataset = as.data.frame(cbind(Y1 = c(rep(0,10), rep(1,10)),
Y2 = c(rep(0,5), rep(1,10), rep(0,5)),
X = rnorm(20, 0, 1)))

#'# Loop with formatted output
#+ Table1, results = 'asis'
for(i in c("Y1", "Y2")){
fit = glm( paste("get(i) ~", "X") ,
family = binomial,
data = dataset)

print(length(fit$residuals))

fit2 = fit %>%
tbl_regression(
exponentiate = TRUE,
conf.level = 0.999,
pvalue_fun = ~style_pvalue(.x, digits = 3),
) %>%
bold_p(t = 0.01) %>%
bold_labels() %>%
italicize_levels()

fit2

print(fit2)
}

脚本2

#'# Print to word document
rmarkdown::render('C:\\Users ... Test.R',
output_format = "word_document",
output_dir = "C:\\Users ...")

最佳答案

我们可以将 print 更改为 knit_print

for(i in c("Y1", "Y2")){
fit = glm( paste("get(i) ~", "X") ,
family = binomial,
data = dataset)

print(length(fit$residuals))

fit2 = fit %>%
tbl_regression(
exponentiate = TRUE,
conf.level = 0.999,
pvalue_fun = ~style_pvalue(.x, digits = 3),
) %>%
bold_p(t = 0.01) %>%
bold_labels() %>%
italicize_levels()

fit2

cat(knitr::knit_print(fit2))
}

render调用中

knitr::opts_chunk$set(
echo=FALSE, warning=FALSE, message=FALSE)
rmarkdown::render(input_file,
output_format = "word_document",
output_dir = output_dir, quiet = TRUE)

-输出

enter image description here

关于r - 来自 R 脚本的循环 tbl_regression 不为 rmarkdown::render 打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69168230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com