How to hide code in RMarkdown, with option to see it

后端 未结 2 417
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 06:32

I\'m writing an RMarkdown document in which I\'d like to re-run some chunks (5 to 9). There\'s no need to display these chunks again, so I considered using

         


        
2条回答
  •  半阙折子戏
    2020-12-13 07:37

    If you add an html tag before your code you can use CSS selectors to do clever things to bits of the output - markdown handily passes the HTML through:

    
    
    
    ```{r} summary(cars) ```

    Here my CSS style rule matches the first

     tag after a 
    and sets it to be invisible. Markdown writes the R chunk with two
     tags - one for the R and one for the output, and this CSS catches the first one.

    Now you know how to match the code and output blocks in CSS, you can do all sorts of clever things with them in Javascript. You could put something in the

    tag and add a click event that toggles the visibility:

    
    
    
    
    [Show Code]
    ```{r} summary(cars) ```

    The next step in complexity is to make the action toggle, but then you might as well use jQuery and get real funky. Or use this simple method. Let's do it with a button, but you also need a div to get your hooks into the R command PRE block, and the traversal gets a bit complicated:

    
    
    
    
    
    ```{r} summary(cars) ```

    ( Note: I thought you could wrap R chunks in

    tags:

    ```{r} summary(cars) ```

    but that fails - anyone know why?)

提交回复
热议问题