I am trying to produce a PDF document with R markdown which includes some equations and r code. I am trying to align sub-items in an un-ordered list which appear after the equations.
Below is the code. I want the words Prediction and Inference to start as new sub items.
---
title: "Test"
author: "Author"
date: "21 April 2018"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
* Main Point
+ **Prediction** - Some text here
$$
\hat{Y}=\hat{f(X)}+\epsilon ............... (2.2)
$$
$$
E( Y - \hat{Y} )^2
= E[f(X) + \epsilon - \hat{f(X)}]^2
=[f(X) - \hat{f(X)}]^2+Var(\epsilon) ......... (2.3)
$$
+ **Inference** - Some text here
No matter what spacing I try, nothing seems to be working. Currently, after the "Main Point", I have given two tabs before the "+" before "Prediction". This works absolutely fine and produces the sub item of the "Main Point". However, after the two equations when I try the same formatting that I did for the first sub-item, it does not work at all and produces the alignment as shown in the picture.
Markdown has a few rules to make sublists work. Most importantly in your case, sub-items only work if there is a parent item to it. As Stackoverflow uses the same syntax, we can show the examples inline. For example:
1. Item
2. Item
* Mixed
* Mixed
Item
Item
Mixed
Mixed
In your case, you have put some none list items between the sub-items, as follows:
1. Item
2. Item
* Mixed
Some Text
* Mixed
Item
Item
Mixed
Some Text
* Mixed
As you can see, the list has been broken and is not recognised as an item.
Workaround
If you are only using PDF output, you are able to use LaTeX commands to achieve custom styling. In your case, you can use the hspace command to add a separation:
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
* Main Point
\hspace{1cm} + **Prediction** - Some text here
$$
\hat{Y}=\hat{f(X)}+\epsilon ............... (2.2)
$$
$$
E( Y - \hat{Y} )^2
= E[f(X) + \epsilon - \hat{f(X)}]^2
=[f(X) - \hat{f(X)}]^2+Var(\epsilon) ......... (2.3)
$$
\hspace{1cm} + **Inference** - Some text here
Related
I'm writing my dissertation in Markdown and it includes a lot of figures in the "results" section. Since I really need all the figures and tables to stay in their order and subsection, I'm keeping them in place with \floatplacement{figure}{H} in the YAML for the figures and kable_styling(latex_options = c("hold_position") for the tables.
My question is, if there's a way to have the text float around the figures without the figures changing their order/section? As soon as I set the floatplacement to h instead of H, they are not staying in their section anymore.
I tried , out.width="1\\textwidth", wrapfigure = list("C", 1) in the code chunk options, which makes the text go on the top of the figure (which is good), but puts the figure ond the next page, even though there would be enough space for it on the current page:
My YAML:
---
output:
bookdown::pdf_document2:
toc: no
fig_caption: yes
includes:
in_header: header.tex
lang: de
geometry: "left=3cm, right=2.5cm, top=2.5cm, bottom=2.5cm"
fontsize: 12pt
bibliography: library.bib
csl: science-modified1.csl
link-citations: yes
linkcolor: black
urlcolor: black
header-includes:
- \usepackage{placeins} #definiert den Befehl \FloatBarrier
- \usepackage{fancyhdr}
- \usepackage[doublespacing]{setspace}
- \usepackage{chngcntr}
- \counterwithout{figure}{section}
- \counterwithout{table}{section}
- \usepackage{microtype}
- \usepackage{amsmath}
- \usepackage{float}
- \floatplacement{figure}{H}
- \usepackage{wrapfig}
- \setlength{\parindent}{1cm}
---
My code chunk options of the figure:
```{r, include = F}
defOut <- knitr::knit_hooks$get("plot") # save the default plot hook
knitr::knit_hooks$set(plot = function(x, options) { # set new plot hook ...
x <- defOut(x, options) # first apply the default hook
if(!is.null(options$wrapfigure)) { # then, if option wrapfigure is given ...
# create the new opening string for the wrapfigure environment ...
wf <- sprintf("\\begin{wrapfigure}{%s}{%g\\textwidth}", options$wrapfigure[[1]], options$wrapfigure[[2]])
x <- gsub("\\begin{figure}", wf, x, fixed = T) # and replace the default one with it.
x <- gsub("{figure}", "{wrapfigure}", x, fixed = T) # also replace the environment ending
}
return(x)
})
```
```{r figure-USB-J01-DDD-absolut-line, fig.cap = "Absoluter Verbrauch von J01-Antibiotika DDDs am USB (auf 30 Tage normiert)", out.width="1\\textwidth", wrapfigure = list("C", 1)}
```
Is there a way to let the text go on top of the figure (e.g. if there is space for it on the previous page, but not the figure) without the figures leaving their sections or behaving weirdly like they did in my example?
I am trying to create an R Markdown file and include a formula. The problem is that when I knit the document the formula appears as I have entered in a latex style.
---
output: github_document
---
$$P(E|L) = \frac{P(L|E) * P(E)}{P(L)} = \frac{0.3 * 0.5}{0.3 * 0.5 + 0.5*1} = 0.23$$
So when I knit it, it looks like:
where as in the code it appears.
What should I do so that when I knit the document, the formula looks like in the second picture?
The problem is coming from your use of the output format github_document. The github output format cannot directly support the maths mode. As stated by the rmarkdown package author in this issue:
I'd say that if you really care about LaTeX math in Markdown, you should render to HTML output instead of waiting indefinitely for Github to support MathJax in Markdown, which I doubt will ever happen.
Implementing his advice, we can change the output format to html_document:
---
output: html_document
---
$$
P(E|L) = \frac{P(L|E) * P(E)}{P(L)} = \frac{0.3 * 0.5}{0.3 * 0.5 + 0.5*1} = 0.23
$$
I want to insert R matrix like m<-rbind(c("x/(z+1)","x^2/(z+1)"),c("y/(z+1)","y^2/(z+1)")) as a table in R Markdown than knit it to .doc.
I would like it in a neat form, such that all cells are separated by lines and all formulas displayed properly. I want to do it automatically from matrix I have.
I am thinking about thous formulas inside the matrix as simple examples of any formula that contains variables and arithmetic operations.
First I tried with more simple expression m<-rbind(c("x","x^2"),c("y","y^2"))
with no result.
TeXForm(m)
library(Ryacas)
Sym(m)
TeXForm(m)
I got:
"$x$";
pander(m)
I got:
-------
A B
--- ---
x x^2
y y^2
-------
formulas in cells were displayed not properly.
knitr::kable(m)
I got:
|A |B |
|:--|:---|
|x |x^2 |
|y |y^2 |
It wasn`t displayed properly in .doc.
xtable(m)
I got LaTeX code which I was unable to knit in .doc. But when knitted in pdf formulas in cells were displayed not properly. I also tried print(xtable(m),type="html")
I wasn`t able to knit it to .doc, but in html document it gives results similar to previous.
Replace each element of matrix with LaTeX code
Apymtx<-function(m,f){m1<-m
for (k in 1:nrow(m)){ for (l in 1:ncol(m)){m1[k,l]<-f(m[k,l])}}
return(m1)}
m<-Apymtx(m, TeXForm)
I got:
[,1] [,2]
[1,] "( TeXForm( x ) )" "( TeXForm( x^2 ) )"
[2,] "( TeXForm( y ) )" "( TeXForm( y^2 ) )"
Than I tried to change 'class' of TeXForm(m[1,1]) to 'character' with no result.
How to get table filed with formulas in R Markdown, and knit it to .doc?
You miss that pandoc interprets Tex formulas between the dollar signs. E.g.:
> pander(data.frame(
+ A = c("$x^2$", "$\\frac{x}{y}$"),
+ B = c("$\\sum_{1}^{n}foobar_i$",
+ "$\\cos (2\\theta) = \\cos^2 \\theta - \\sin^2 \\theta$")))
--------------------------------------
A B
------------- ------------------------
$x^2$ $\sum_{1}^{n}foobar_i$
$\frac{x}{y}$ $\cos (2\theta) = \cos^2
\theta - \sin^2 \theta$
--------------------------------------
Renders fine in docx:
Edit: based on the question update that made it clearer for me that you want to transform the math formulas to TeX by Ryacas, please see this approach to do so. Unfortunately, I could not get the retclass="unquote" argument working in yacas, that's why the ugly string manipulation:
> pander(apply(m, c(1, 2), function(x) gsub('\\"|;| ', '', yacas(TeXForm(x))$YacasForm)))
--------------- -------------------
$\frac{x}{z+1}$ $\frac{x^{2}}{z+1}$
$\frac{y}{z+1}$ $\frac{y^{2}}{z+1}$
--------------- -------------------
MS Word output after calling pander:
Here is another variant of solution based on answer marked as correct.
library(Ryacas)
library(pander)
m<-rbind(c("x","x^2"),c("y","y^2"))
Apycs<-function(m){
library(Ryacas)
m1<-m
for (k in 1:nrow(m)){ for (l in 1:ncol(m)){
m.2<-yacas(TeXForm(m[k,l]))[[2]]
m1[k,l]<-substr(m.2,2,nchar(m.2)-2)}}
return(m1)}
m<-Apycs(m)
pander(m)
I would like to place the caption above the figure using knitr in texmaker.
I know that this question has already been asked, and I understand that the solution suggested so far is to use:
\begin{figure}
\caption{This is a caption above the figure}
<<a-plot, echo=FALSE>>=
plot(1)
#
\end{figure}
But in this way I cannot show the code (since echo=FALSE).
And if I choose instead echo=TRUE, what I get is the caption, then the codes, and then the graph, which is also not what I want.
What I would like to show is the code for R, (and) the graph plotted with that R code, with the caption above the graph.
My preference tends to be to use LaTeX packages to achieve customisation like this: there is a large community on Tex StackExchange who have developed methods to load of problems similar to this.
The floatrow package can be used to reposition the caption above the figure. This is largely based on this previous answer.
Using R Markdown, as this is the most typically used workflow these days, the package can be loaded by including header-includes argument within the YAML, as follows:
---
output: pdf_document
header-includes:
- \usepackage{floatrow}
- \floatsetup[figure]{capposition=top}
---
```{r fig.cap="cap, cap, and cap"}
plot(1)
```
The output has the desired order with the code displayed first, followed by the caption then the plot.
If the code is not wanted, the echo=FALSE option can be added to the chunk header.
Try using hook:
<<include=FALSE>>=
f <- function(x, options) {
paste("\\end{kframe}\n",
"\\caption{", options$capT, "}\n",
hook_plot_tex(x, options),
"\n\\begin{kframe}", sep = "")
}
knit_hooks$set(plot = f)
#
\begin{figure}
<<a-plot, echo=TRUE, capT="cap, cap, and cap">>=
plot(1)
#
\end{figure}
This is a slighty modified version of kohske's answer, that includes \begin{figure} and adds \label. Note however that it contains 5 lines, while the original code contains more than 150 lines, so it should be used in very limited settings.
f <- function(x, options) {
lab <- paste0(options$fig.lp, options$label)
paste("\\end{kframe}\n",
"\\begin{figure}\n\\caption{", options$capT, "}\\label{", lab,"}\n",
hook_plot_tex(x, options),
"\\end{figure}\n\n\\begin{kframe}", sep = "")
}
knit_hooks$set(plot = f)
Add a new block below it, with the same name, to print the code.
\documentclass{article}
\begin{document}
\begin{figure}
\caption{This is a caption above the figure}
<<a-plot, echo=FALSE>>=
plot(1)
#
\end{figure}
<<a-plot,echo=TRUE>>=
#
\end{document}
Not sure if LaTeX counts as programming, or if my question even makes sense, but I have this LaTeX expression (or what you call it):
\sum_{k=1}^n k^2 = 1+4+9+\ldots +n^2 =
\frac{1}{3}n^3 + \frac{1}{2}n^2 + \frac{1}{6}n
The problem is that the k=1 and n comes next to, i.e. after, the sum symbol, instead of above and below it. Is there a way I can change this? I have tried to show visually what I mean below. The sum symbol represented as Xs :
n
XXX XXX n
XXX vs XXX
XXX XXX k=1
k=1
I want the first kind, but am getting the second.
Try
\sum\limits_{k=1}^n k^2
if you want the sum limits to appear above and below the sum sign in an inline equation.
A more general solution to force a formula that is appearing in inline style to appear in display style is to start the formula with a \displaystyle declaration, e.g.
$\displaystyle \sum_{k=1}^n k^2$
This will work for any expression that appears differently in inline and display environments, such as \frac, \int, \lim, etc. You can also control the scope of the \displaystyle command by enclosing the desired expression in braces. For example, if you want the sum in your example formula to appear in display style but not the fractions, you could use
${\displaystyle \sum_{k=1}^n k^2} = 1+4+9+\ldots +n^2 =
\frac{1}{3}n^3 + \frac{1}{2}n^2 + \frac{1}{6}n$
I think you will need to use the equation environment for that:
\begin{equation}
\sum_{k=1}^n k^2 = 1+4+9+\ldots +n^2 = \frac{1}{3}n^3 + \frac{1}{2}n^2 + \frac{1}{6}n
\end{equation}