Is there anyway to format code in the "code" format offered by many websites like Stackoverflow in R Markdown.
I want to be able to do something like the following:
Any model that takes the form income ~ education + parental_income
...
I want to emulate that greyed out text in R markdown for ease of readability when I eventually knit the document.
One can use backticks or indenting by 4 spaces to generate the equivalent of the HTML <code> </code> tag block. Here is an Rmd document illustrating this behavior.
---
title: "Sample Document"
author: "bigNumber"
date: "12/5/2017"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
here is some example code written in R Markdown. If we want to enter a code block we use the backtick, such as `inc ~ ed + occ`.
If we want a code block with multiple lines, indenting by 4 spaces also works
# first line of code
for(i in 1:100) {
# do something here
}
More text after the code block ends.
...and the output. Unfortunately I have to include an image to show that it renders correctly.
```
If you'd rather not
indent your code block by four spaces, you can use
triple back-ticks on separate lines.
```
https://bookdown.org/yihui/rmarkdown/markdown-syntax.html#block-level-elements
html could work if you want to have a string with gray color as a background
Changing chunk background color in RMarkdown
Related
When you use inline code in an R Markdown document, the code is evaluated and the output is incorporated into the text. For example,
The sum of 2 and 2 is `r 2+2`.
This will generate the following text in the .nb.html file:
The sum of 2 and 2 is 4.
That text is not styled or tagged in any way in the HTML output, so there is no way to apply CSS.
But I'd like to be able to see in the HTML document if text appears "as is" or if it was processed through inline code. In other words, I want to know see a difference in the appearance of the number 4 if I write
The sum of 2 and 2 is `r 2+2`.
versus
The sum of 2 and 2 is 4.
Is there any way to do this?
(The use case here is that I have students who are supposed to use inline code in their assignments, but if I'm looking at the .nb.html file and not the .Rmd file, I can't tell if they just manually typed in an answer without using code to generate it.)
EDIT: My original question said R Markdown, and there is a good solution to that question below. However, I need this to work in an R Notebook, and it seems that knit_hooks$set is ignored when creating the HTML file.
One possible way is using knitr::knit_hooks$set.
---
title: "Untitled"
author: "Shafayet Khan"
date: "2022-07-31"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
random_class <- paste0("class-", round(runif(1, 200, 2000)))
styleIt <- function(x) {
paste0("<span class='", random_class, "' style=\"color: red;\">", x,"</span>")
}
knitr::knit_hooks$set(inline = styleIt)
```
## R Markdown
### inline code
The sum of 2 and 2 is `r 2+2`
### not inline code
The sum of 2 and 2 is 4.
### Manually styled
The sum of 2 and 2 is <span style="color: red;">4</span>
When rendered, it looks like
Now note that the students always can use the span tag to get the same color as the inline code, so to make a difference, I have used a randomly generated class and used that for inline code, so when you have the HTML file, span tag for an inline code should have a randomly generated class name like class-672 while manually typed and colored code will unlikely have that same class name. Hope this helps.
I think the question is quite self-explanatory but for avoidance of doubt I'll explain with more detail below:
I have an R Markdown document that works well if converted to HTML or uploaded to GitHub. When converting to PDF (using Latex), the results are not so pretty. I find that the biggest problem in a Latex PDF document are line breaks. I can fix the line breaks issue on the PDF document by adding "\ " characters, but that throws my HTML document out of whack too.
Is there a way to manually add line breaks (or "space before/after paragraphs") for the PDF output only?
Thank you!
You can redefine the relevant spacings in the YAML header. \parskip controls the paragraph spacing. Code blocks are shaded using a snugshade environment from the framed package. We can also redefine the shaded environment for code blocks to have some vertical space at the start. Here's a reproducible example. Note: I also added the keep_tex parameter so you can see exactly what the generated tex file looks like, in case this is useful:
title: "test"
author: "A.N. Other"
header-includes:
- \setlength{\parskip}{\baselineskip}
- \renewenvironment{Shaded}{\vspace{\parskip}\begin{snugshade}}{\end{snugshade}}
output:
pdf_document:
keep_tex: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Once you output to HTML, you can just print the HTML webpage as PDF. that might be an easy way keep the original format
I'm working in Rmarkdown and knitting to PDF. I want to start a paragraph with (a) without creating a list. Adding \(a) works, but it highlights the rest of my Rmd file text, making it hard to read. Is there another way to indicate that I do not want to create a list in Rmarkdown?
---
title: "Untitled"
output:
pdf_document: default
html_document: default
---
This is the first paragraph.
```{r, include=FALSE}
1+1 # nice highlighting before problem
```
(a) This should be the second paragraph. (b) But it is interpreted as a list.
\(a) This slash works to keep the text as a paragraph, but it highlights all remaining text in my Rmd file, which makes it hard to read. (b) Is there another method to use (a) without creating a list?
Here is a good list, but still wrong color in Rmd:
(a) One
(b) Two
```{r, include=FALSE}
1+1 # bad highlighting after problem
```
Try putting (a) in <span> like
<span> (a) </span> This should be the second paragraph.
It's a bit hacky but it works for html & pdf and it fixes the highlighting problem.
Instead of the element placing a on the previous line works. If there is actual text on the previous line then ending the line with two spaces also works.
I am trying to add a cover page which is already created in a PDF.
```{r echo=FALSE,out.width='8.27in',out.height='11.69in'}
knitr::include_graphics('CoverPage.pdf')
```
I want to change the margins of the first page only. Can you please help me with this?
The following was tried but it changes the margin of the whole document:
geometry: "left=3cm,right=3cm,top=2cm,bottom=2cm"
If you are fine with some bare LaTeX in your RMD file, then this can be easily achieved using the geometry package. Just define a newgeometry before the cover is included and restoregeometry afterwards (reads almost like English …).
---
output:
pdf_document
---
```{r, echo = FALSE, results = "asis"}
cat("\\newgeometry{left=3cm,right=3cm,top=2cm,bottom=2cm}")
knitr::include_graphics("CoverPage.pdf")
cat("\\restoregeometry")
```
\clearpage
Note the position of the page number. Restoring the margins was successful!
It is important to use the chunk option results="asis" and cat() to print raw LaTeX and to escape the backslashes with an additional backslash.
I am making some slides inside Rstudio following instructions here:
http://rmarkdown.rstudio.com/beamer_presentation_format.html
How do I define text size, colors, and "flow" following numbers into two columns?
```{r,results='asis', echo=FALSE}
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
cat(rd, sep = "\n")
```
Output is either HTML (ioslides) or PDF (Beamer)
Update:
Currently the code above will only give something like the following
6683209
1268680
8412827
9688104
6958695
9655315
3255629
8754025
3775265
2810182
I can't do anything to change text size, color or put them into a table. The output of R codechunk is just plain text. Maybe it is possible to put them in a table indeed, as mentioned at this post:
http://tex.aspcode.net/view/635399273629833626273734/dynamically-format-labelscolumns-of-a-latex-table-generated-in-rknitrxtable
But I don't know about text size and color.
Update 2:
The idea weaving native HTML code to R output is very useful. I haven't thought of that. This however only works if I want to output HTML. For PDF output, I have to weave the native Latex code with R output. For example, the code following works using "knitr PDF" output:
```{r,results='asis', echo=FALSE}
cat("\\textcolor{blue}{")
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
for (n in rd) {
cat(paste0(n, '\\newline \n')) }
cat("}")
```
You are using results='asis', hence, you can simply use print() and formatting markup. If you want your text to be red, simply do:
```{r,results='asis', echo=FALSE}
print("<div class='red2'>")
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
cat(rd, sep = "\n")
print("</div>")
```
Hope it helps.
It sounds as if you want the output to be either PDF or HTML.
One possibility is the xtable package. It produces tables either in PDF or HTML format. There's no (output-independent) way to specify colour, however. Here's an example.
xt <- xtable(data.frame(a=1:10))
print(xt, type="html")
print(xt) # Latex default
Another option is the pandoc.table function from the pander package. You need the pandoc binary installed. If you have RStudio, you have this already. The function spits out some markdown which then can be converted to HTML or PDF by pandoc.
Here's how you could use this from RStudio. Create an RMarkdown document like this:
---
title: "Untitled"
author: "You"
date: "20 November 2014"
output: html_document
---
```{r, results='asis'}
library(pander)
tmp <- data.frame(a=1:10,b=1:10)
pandoc.table(tmp)
```
When you click "knit HTML", it will spit out a nice HTML document. If you change output to pdf_document, it will spit out a nice PDF. You can edit the options to change output - e.g.
pandoc.table(tmp, emphasize.strong.rows=c(2,4,6,8,10))
and this will work both in PDF or HTML. (Still no options to change colour though. Homework task: fix pandoc.table to allow arbitrary colours.)
Under the hood, knitr is writing markdown, and pandoc is converting the markdown to whatever you like.