6

I would like to try to produce reports (pdf and probably html) in jupyter using R kernel. However, I would like to hide code in two ways, depending on audience:

  1. all code cells
  2. some code cells

When I have looked for this I found answers for python kernel. Is there a way to this in R (no python code)?

Bartek
  • 173
  • 1
  • 9

3 Answers3

9

So I have started to combine python's answer: How to hide code from cells in ipython notebook visualized with nbviewer? with How to render LaTeX / HTML in Jupyter (R)? and it works. If one puts the following code in a cell, will get a button for hiding code. From here I think I know where to start.

library(IRdisplay)

display_html(
'<script>  
code_show=true; 
function code_toggle() {
  if (code_show){
    $(\'div.input\').hide();
  } else {
    $(\'div.input\').show();
  }
  code_show = !code_show
}  
$( document ).ready(code_toggle);
</script>
  <form action="javascript:code_toggle()">
    <input type="submit" value="Click here to toggle on/off the raw code.">
 </form>'
)
Community
  • 1
  • 1
Bartek
  • 173
  • 1
  • 9
  • Thanks so much. This allows me to give html exported notebooks to people rather than having to mess with markdown! – cs0815 Feb 13 '21 at 11:55
  • Adaptation for JupyterLab: https://stackoverflow.com/questions/70617446/the-function-display-html-not-working-in-jupyter-lab/71937773#71937773 – krassowski Apr 20 '22 at 10:11
2

As you're talking about making HTML and PDF reports, you can do this by using a custom template with nbconvert, and using that to hide cells. This will work for any notebook, independent of the kernel you use.

Docs on nbconvert templates: http://nbconvert.readthedocs.org/en/latest/customizing.html

Examples including hiding code cells based on cell metadata: https://github.com/jupyter/ngcm-tutorial/tree/master/Day-2/nbconvert_templates

Thomas K
  • 39,200
  • 7
  • 84
  • 86
0

Add some CSS code in the first cell, change that cell to 'Raw NBConvert' and the format specified in the CSS will be applied to the HTML generated:

To hide input blocks:

<style type="text/css">
.input_hidden{
    display: none
}
</style>

Other style definition can also go there.

Then run ipython nbconvert the_name_of_the_stuff.ipynb --to slides to generate the HTML (without the input blocks).

CT Zhu
  • 52,648
  • 17
  • 120
  • 133