xiaodai
xiaodai

Reputation: 16064

RMarkdown: is it possible to return a table and a chart from the same cell?

I write a function that takes some data and outputs a table and a plot. And I want to show the table and the plot one after the other.

But I can't seem to find a function in Rmarkdown that can do that and instead have to break it up into two.

E.g this is what I want to have

plot_and_table <- function(input_data) {
  output_data = ... do some to input_data
  plot = plot(.... something about output_data)
  list(plot, output_data)
}

plot_and_table(input_data)

and have the plot plotted before printing the table in the same flow.

Upvotes: 0

Views: 246

Answers (1)

stomper
stomper

Reputation: 1385

Consider using patchwork?

library(patchwork)
plot_and_table <- function(input_data){
    output_data = input_data[1:5, c('mpg', 'disp')]
    
    p1 <- ggplot(output_data) + 
        geom_point(aes(mpg, disp)) + 
        ggtitle('Plot 1')
    p2 <- gridExtra::tableGrob(output_data)
 return(p1/p2)
}

plot_and_table(mtcars)

    

result

Upvotes: 3

Related Questions