I would appreciate some suggestions of a good way to prepare a report using rmarkdown, in which I loop through subsets of a data set, creating a plot of each subset, and interspersing among the figures some text relevant to each figure.
One way is to have an R script write the rmd file, then render it. It works, but it's cumbersome and difficult to get the rmd syntax correct. I would very much appreciate suggestions for a better way. Reproducible example below. Thanks -Don Example data (other data structures could be used), and an example using this approach. myd <- lapply( 1:3, function(i) list(df=data.frame(x=1:5, y=rnorm(5)), comment=paste('Data', LETTERS[i])) ) Example interactive review (details would change depending on data structure) (I would typically insert pauses when working interactively) for (i in 1:3) { cat(paste('Figure',i,'shows',myd[[i]]$comment),'\n') with(myd[[i]]$df , plot(x,y)) mtext(myd[[i]]$comment) mtext( paste(nrow(myd[[i]]$df),'points'), adj=1) } Note that along with the data I've saved some comments relevant to each subset. I've calculated them in the example data, but in general they could be completely arbitrary and come from anywhere. Now I'd like to get the same plots and comments into a report prepared using rmarkdown. Here's one way, having the loop create an rmd file, then rendering it. ### example script begins library(rmarkdown) myf <- 'myd.rmd' sink(myf) cat('--- title: Example --- Here are some figures with a comment appearing before each.\n\n' ) sink() for (i in 1:3) { cat(paste('Figure',i,'comment:',myd[[i]]$comment),'\n', file=myf, append=TRUE) cat(" ```{r echo=FALSE, fig.cap='",paste('fig',i),"caption.'} with(myd[[",i,"]]$df , plot(x,y)) mtext(myd[[",i,"]]$comment) mtext( paste(nrow(myd[[",i,"]]$df),'points'), adj=1) ``` ", file=myf, append=TRUE) } cat('Done with report\n', file=myf, append=TRUE) render(myf) -- Don MacQueen Lawrence Livermore National Laboratory 7000 East Ave., L-627 Livermore, CA 94550 925-423-1062 Lab cell 925-724-7509 ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.