Bart
Bart

Reputation: 493

R: How can I code repetitive output into an Rmarkdown file?

I am doing complex exploratory analysis on a data set. I have created a function that will take the desired variables, run and evaluate several models then return a list with various results and plots. I can easily run this on the different combinations of predictor and outcome variables. I would also like to create a "function" or repeatable script that will display the results in the rmarkdown output, so I don't have to edit every chunk when I want to make a change to the output. (For instance, I just added a sensitivity analysis to the function, but now I have to edit about 45 chunks to get the results to display.)

Simplified Example:

#Packages used: dplyr, knitr, kableExtra, pander

data("airquality")
lm.1 <- lm(Solar.R ~ Wind, data = airquality, na.action = na.omit)
lm.2 <- lm(Solar.R ~ Wind + Temp, data = airquality, na.action = na.omit)

#The real output list is bigger/more complex:
myList <- list(model.1 = lm.1,  model.2 = lm.2, bic = BIC(lm.1,lm.2))


#Create a character vector containing each line of display code I wish to run:  

myDisplay <- c("kable('Model Comparisons', col.names = NULL) %>%
                  kable_styling(bootstrap_options = 'striped', font_size = 20)",
               "pander(myList$bic)",
               "kable('Full Model Summary', col.names = NULL) %>%
                  kable_styling(bootstrap_options = 'striped', font_size = 20)",
               "pander(myList$model.2)")

For each analysis output list I create, I want to run what is in myDisplay. So in the following chunks, I tried:

{r, eval = T, results = 'asis'} #I tried with and without "asis"
for(i in myDisplay){
  eval(parse(text = i))
}

When I run that for loop in the console, I get the expected outputs, but when I knit my rmarkdown file, I literally get nothing from it. No warnings, messages, errors, or anything at all.

Is there a way to do this? Does it have to do with eval(parse(text = .))? Is there something else to try?

Post Script:
@Aaron Montgomery's suggestion to add cat(eval(parse(text=i))) worked. There was one small problem with my real code. One of the list items was a plot returned by ggplot(). cat() could not handle that request. That's okay as it is easy to workaround.

My code chunks for each analysis now look something like this:

{r, results = 'asis'}
myList <- myFunction(X,Y,Z)
myList$plot
for(i in myDisplay){
  cat(eval(parse(text = i)))
}

Now I only have to edit myFunction and myDisplay to change the entire document.

Upvotes: 1

Views: 174

Answers (1)

Aaron Montgomery
Aaron Montgomery

Reputation: 1407

Try wrapping your eval in cat() (concatenate and print) to coax R to write something down:

{r, eval = T, results = 'asis'} #I tried with and without "asis"
for(i in myDisplay){
  cat(eval(parse(text = i)))
}

Upvotes: 1

Related Questions