Include R Output in your Blog Pages with Opencpu

1 minute read

Todays blog post is more a note than a full blog post.

On my previous post, opencpu was used to create a back-end environment for a flexdashboard dashboard.

On that post, I use a bit of js to include dynamic plot into my web page.

Set up

It is possible to include js directly in your .rmd. I prefer for small piece of code to use htmltools but it is not mandatory:

# client library for opencpu: 
htmltools::tags$script(src="https://code.jquery.com/jquery-1.11.1.min.js") 
htmltools::tags$script(src="https://cdn.opencpu.org/opencpu-0.4.js") 
 # set page to communicate to with "mypackage" on server below 
htmltools::tags$script("ocpu.seturl('https://yvescr.ocpu.io/flexocpu/R')")

Plot

Now, we use the .rplot function to call plot. here, with a parameter of 1.

It is indeed useless if the plot is not a dynamic one. It is better in that case to include a fixed image.

The code used to include this post:

<script> 
$(function(){  
  $("#plottest").rplot("plotind", {id : Number(1)}); 
}) 
</script> 
 
<div id="plottest" style="height: 270px"> 

Dynamic plot

With a bit of js, we can easily complexify the process to make it reactive:

<script>  
 
$(function(){ 
 
  $('container-fluid main-container').css({'visibility': 'visible'}); 
   
  var paramid = 1; 
 
  var req = $("#plotdiv").rplot("plotind", {id : Number(paramid)}); 
 
  var req2 = ocpu.rpc("gethowel", {id : Number(paramid)}, 
      function(output){ console.log(output)}); 
 
  $("#idsubmit").click(function(e){ 
   
  var paramid = $("#myid").val(); 
   
    var req = $("#plotdiv").rplot("plotind", {id : Number(paramid)}); 
   });  
});    
</script>

And the interface:

htmltools::tags$input(type="integer", class="form-control", id="myid", value="1", style = "width: 90%;") 
htmltools::tags$button("Update dashboard!", type="submit", id="idsubmit", class="btn btn-default")
htmltools::tags$div(id="plotdiv", style="height: 270px")

The result is a dynamic plot inside the blog post.

You can enter any integer between 1 and 544:

The same can be done to create dynamic json or any htmlwidget output.

Leave a Comment