2016-06-16 14 views
6

Sto scrivendo un rapporto in Rmarkdown che deve essere visualizzato in html perché contiene blocchi Rshiny. C'è un modo per aggiungere numeri di riga al file?Aggiungere numeri di riga al contenuto di testo di un documento html rmarkdown renderizzato

È importante sottolineare che ho bisogno di numeri di riga per il testo e non per i pezzi di codice come chiesto here.

Mi chiedo se sia possibile aggiungere alcuni CSS al file .Rmd di seguito, ma non saprei come farlo.

--- 
title: "Title" 
author: "Yourname" 
date: "June 16, 2016" 
output: html_document 
runtime: shiny 
--- 


This R Markdown document is made interactive using Shiny. 
Unlike the more traditional workflow of creating static reports, you can now create documents that allow your 
readers to change the assumptions underlying your analysis and see the results immediately. 

## Inputs and Outputs 

You can embed Shiny inputs and outputs in your document. Outputs are automatically updated whenever inputs change. 
This demonstrates how a standard R plot can be made interactive by wrapping it in the Shiny `renderPlot` function. 
The `selectInput` and `sliderInput` functions create the input widgets used to drive the plot. 

La ringrazio molto,

Paul

risposta

6

Domanda interessante e dato che mi piace giocare con JS e jQuery all'interno di documenti RMarkdown ho dato un colpo.

Questa soluzione non è a prova di proiettile. È testato solo con Firefox. Dal momento che la compatibilità cross-browser di jQuery è un disastro, probabilmente funzionerà solo con Firefox.

Ogni riga viene ora etichettata includendo i paragrafi normali, gli elenchi non ordinati e ordinati, il codice sorgente e i blocchi di output.

Ecco il documento di lavoro completo:

--- 
title: "Title" 
author: "Yourname" 
date: "June 16, 2016" 
output: html_document 
runtime: shiny 
--- 

<style> 
    /* Style the linenumber div */ 

    .linenumbers { 
    border: 1px solid #ccc; 
    border-radius: 4px; 
    background-color: #EBEBEB; 
    text-align: center; 
    padding: 0px 3px; 
    font-family: monospace; 
    float: left; 
    position: absolute; 
    transform:translate(-125%); 
    font-size: inherit !important; 
    } 

    .main-container { 
    margin-left: 8% !important; 
    } 

    /* fixes the problem with inline code 
    that makes the line spacing bigger: */ 
    p > code { 
    line-height: 90% !important; 
    } 
</style> 


<script> 
    var $elements = $('p:not(:has(>img)), pre, ul, ol').slice(start=1); 

    $(document).ready(function(){ 
    $elements.wrap('<numbering/>'); 
    $('numbering').prepend('<div class=\"linenumbers\"/>'); 

    updateLines = function(elmts) { 
     var counter = 1; // counts total number of lines 
     $(elmts).each(function() {  

     if($(this).is('pre')) { 
      var $elmt = $(this).children('code'); 
      var styles = $(this).css([ "padding-top", "padding-bottom", "line-height"]); 
      $(this).siblings('.linenumbers').css(styles); 
     } else { 
      var $elmt = $(this); 
     } 

     var h = $elmt.outerHeight(); // get the height 
     var nl = Math.round(h /parseFloat($elmt.css('line-height'))); 
     var text = ''; 
     for(var i=counter; i < counter + nl; ++i) { 
      text += i + '</br>'; 
     } 
     counter += nl; 
     $(this).siblings('.linenumbers').html(text); 
     }); 
    }; 
    updateLines($elements); 

    }); 

    $(window).resize(function() { 
    updateLines($elements); 
    }); 
</script> 

This R Markdown document has the ability to interactively number 
the lines of text content. It might not be perfect but it sure 
looks nice. If you find a bug or have a tip for how to further improve 
the code, please let me know. I am no professional JavaScript 
programmer so this was made by an amateur ;) 


What if I leave some space here? 


## Inputs and Outputs 

Here starts another paragraph. Look how the line numbers jump over to 
this one! This is amazing! For demonstrating purposes I have to write 
some more lines. So I bore you a bit more with my nonsense. NONSENSE! 
Ok let us try out some inline code and see whether the line numbers 
still align. `library(ggplot2)` And a second `time()`. Looks ok I 
guess. 
Here starts another paragraph. Look how the line numbers jump over to 
this one! This is amazing! For demonstrating purposes I have to write 
some more lines.  
So I bore you a bit more with my nonsense. NONSENSE! Ok let us try out 
some inline code and see whether the line numbers still align. 
`library(ggplot2)` And a second `time()`. Looks ok I guess. 

```{r} 
x <- 1:5 
B <- 'Martin' 
head(mtcars) 
``` 

```{r} 
plot(1) 
``` 

È possibile escludere alcune parti semplicemente rimuovendo il tag corrispondente dalla linea

var $elements = $('p:not(:has(>img)), pre, ul, ol').slice(start=1); 

Quindi, se non si vuole etichettare pezzi di uscita e liste, modificarlo in

var $elements = $('p:not(:has(>img)), pre.r').slice(start=1); 

(A differenza dei blocchi di output, blocchi di codice sorgente portare la classe .r.)

Come ho detto per i documenti complessi, potresti inciampare in alcuni bug. Fatemi sapere se si fa;)

enter image description here

+0

Questo è incredibile! Come possiamo ottenere la numerazione per includere i blocchi di codice? Ho provato a mettere intorno a loro ma non ha avuto alcun effetto. – Ben

+0

Martin, grazie mille! Un grande passo avanti nella stesura di un paper per conferenze in rmarkdown con elementi Shiny. Ho notato due cose. Funziona in Firefox 47.0 ma non in Chrome 51.0 sul mio computer. Inoltre, se esiste una riga vuota libera all'interno dei tag , interrompe la numerazione. Qualche idea? – Paul

+1

Paul e @ Ben: Grazie e benvenuto. Ho esaminato i problemi. La prima cosa che posso dire è che questi meccanismi jQuery non sono compatibili con i browser, quindi dovresti attenersi a Firefox. Domani aggiornerò la risposta con un nuovo codice che supporta blocchi di codice sorgente. –

Problemi correlati