首先,我必须承认我对 knitr 和可重现分析的概念还很陌生,但我可以看到它在改进我当前的工作流程(其中包括大量复制粘贴到 word 文档中)方面的潜力。
我经常需要按组(在本例中为医院)生成多个报告,并且在每家医院内,我可能会报告许多不同的病房结果。以前我使用循环在 R 中运行我的所有绘图和分析,然后开始复制/粘贴工作;然而,在阅读了这篇文章后(Sweave 可以自动生成许多 pdf 文件吗?),它给了我希望,我实际上可以跳过许多步骤,直接从 R 到 Rnw/knitr 报告。
但是,在尝试之后,我发现有些东西不太有效(因为 Rnw 中的 R 环境似乎无法识别我试图传递给它的循环变量??)。
## make my data
Hospital <- c(rep("A", 20), rep("B", 20))
Ward <- rep(c(rep("ICU", 10), rep("Medicine", 10)), 2)
Month <- rep(seq(1:10), 4)
Outcomes <- rnorm(40, 20, 5)
df <- data.frame(Hospital, Ward, Month, Outcomes)
## Here is my current work flow-- produce all plots, but export as png and cut/paste
for(hosp in unique(df$Hospital)){
subgroup <- df[ df$Hospital == hosp,]
for(ward in unique(subgroup$Ward)){
subgroup2 <- subgroup[subgroup$Ward == ward,]
savename <- paste(hosp, ward)
plot(subgroup2$Month, subgroup2$Outcomes, type="o", main=paste("Trend plot for", savename))
}
}
# followed by much copy/pasting
## Here is what I'm trying to go for using knitr
library(knitr)
for (hosp in unique(df$Hospital)){
knit("C:file.path\\testing_loops.Rnw", output=paste('report_', Hospital, '.tex', sep=""))
}
## With the following *Rnw file
## start *.Rnw Code
\documentclass[10pt]{article}
\usepackage[margin=1.15 in]{geometry}
<<loaddata, echo=FALSE, message=FALSE>>=
Hospital <- c(rep("A", 20), rep("B", 20))
Ward <- rep(c(rep("ICU", 10), rep("Medicine", 10)), 2)
Month <- rep(seq(1:10), 4)
Outcomes <- rnorm(40, 20, 5)
df <- data.frame(Hospital, Ward, Month, Outcomes)
subgroup <- df[ df$Hospital == hosp,]
@
\begin{document}
<<setup, echo=FALSE >>=
opts_chunk$set(fig.path = paste("test", hosp , sep=""))
@
Some infomative text about hospital \Sexpr{hosp}
<<plots, echo=FALSE >>=
for(ward in unique(subgroup$Ward)){
subgroup2 <- subgroup[subgroup$Ward == ward,]
# subgroup2 <- subgroup2[ order(subgroup2$Month),]
savename <- paste(hosp, ward)
plot(subgroup2$Month, subgroup2$Outcomes, type="o", main=paste("Trend plot for", savename))
}
@
\end{document}
## To be then turned into pdf with this
tools::texi2pdf("C:file.path\\report_A.tex", clean = TRUE, quiet = TRUE)
尝试运行我的 knit() 代码块后,我收到此错误:
Error in file(con, "w") : invalid 'description' argument
当我查看要创建 *.tex 文件的目录时,我可以看到医院 A 的 2 个 pdf 图已生成(B 没有),并且没有医院特定的 *.tex 文件可以编织成 pdf。提前感谢您提供的任何帮助!