Missing text in PDF after R chunk in Lyx/knitr - knitr

I'm using Lyx 2.1.2 with knitr on a Fedora 20 x86_64 system. I'm not sure how to determine the version of knitr, but it is certainly working, generally providing very good results. However I see two problems: (1) If I include the final # in any of the chunks, it appears literally in the text. Naturally I don't mind if I don't have to add the final #. It's implied by the end of the chunk, anyway. However (2) if I do NOT include the final # in Chunk 3 (see below), then all of the document text between Chunks 3 and 4 vanishes from the PDF output.
In working to create a minimal example (sorry for not posting one before), I find that the key to the behaviour is the presence of the Medium Vertical Skip immediately after Chunk 3. If I delete that, the document text is output just fine.
I don't see a way to attach files to this post, so I'll include them in the text. Just let me know if there's a better way to post examples. This file is minimal.lyx:
#LyX 2.1 created this file. For more info see http://www.lyx.org/
\lyxformat 474
\begin_document
\begin_header
\textclass article
\use_default_options true
\begin_modules
knitr
\end_modules
\maintain_unincluded_children false
\language american
\language_package default
\inputencoding auto
\fontencoding global
\font_roman default
\font_sans default
\font_typewriter default
\font_math auto
\font_default_family default
\use_non_tex_fonts false
\font_sc false
\font_osf false
\font_sf_scale 100
\font_tt_scale 100
\graphics default
\default_output_format default
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize default
\spacing single
\use_hyperref false
\papersize a4paper
\use_geometry false
\use_package amsmath 1
\use_package amssymb 1
\use_package cancel 1
\use_package esint 1
\use_package mathdots 1
\use_package mathtools 1
\use_package mhchem 1
\use_package stackrel 1
\use_package stmaryrd 1
\use_package undertilde 1
\cite_engine basic
\cite_engine_type default
\biblio_style plain
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date false
\justification true
\use_refstyle 1
\index Index
\shortcut idx
\color #008000
\end_index
\secnumdepth 3
\tocdepth 3
\paragraph_separation indent
\paragraph_indentation default
\quotes_language english
\papercolumns 1
\papersides 2
\paperpagestyle default
\tracking_changes false
\output_changes false
\html_math_output 0
\html_css_as_file 0
\html_be_strict false
\end_header
\begin_body
\begin_layout Standard
\begin_inset Flex Chunk
status open
\begin_layout Plain Layout
<<import-external-code,echo=FALSE>>=
\end_layout
\begin_layout Plain Layout
read_chunk('mini.R')
\end_layout
\end_inset
\end_layout
\begin_layout Section
Section A
\end_layout
\begin_layout Standard
Some text
\end_layout
\begin_layout Standard
\begin_inset Flex Chunk
status open
\begin_layout Plain Layout
<<Mini1,echo=FALSE>>=
\end_layout
\end_inset
\begin_inset VSpace medskip
\end_inset
\end_layout
\begin_layout Standard
Explanation of first graph
\end_layout
\begin_layout Subsection
Subsection A1
\end_layout
\begin_layout Standard
Some text
\end_layout
\begin_layout Standard
\begin_inset Flex Chunk
status open
\begin_layout Plain Layout
<<Mini2,echo=FALSE>>=
\end_layout
\end_inset
\end_layout
\begin_layout Standard
Explanation of second graph
\end_layout
\end_body
\end_document
The referenced R code (mini.R) is trivial:
# ---- Mini1
print("Hello World")
# ---- Mini2
print("Where did the explanation of the first graph go?")
This is the minimal.tex output from pdflatex:
\batchmode
\makeatletter
\def\input#path{{/home/loga/bug//}}
\makeatother
\documentclass[a4paper,twoside,american]{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin#nat#width>\linewidth
\linewidth
\else
\Gin#nat#width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.345, 0.345, 0.345}
\newcommand{\hlnum}[1]{\textcolor[rgb]{0.686,0.059,0.569}{#1}}%
\newcommand{\hlstr}[1]{\textcolor[rgb]{0.192,0.494,0.8}{#1}}%
\newcommand{\hlcom}[1]{\textcolor[rgb]{0.678,0.584,0.686}{\textit{#1}}}%
\newcommand{\hlopt}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlstd}[1]{\textcolor[rgb]{0.345,0.345,0.345}{#1}}%
\newcommand{\hlkwa}[1]{\textcolor[rgb]{0.161,0.373,0.58}{\textbf{#1}}}%
\newcommand{\hlkwb}[1]{\textcolor[rgb]{0.69,0.353,0.396}{#1}}%
\newcommand{\hlkwc}[1]{\textcolor[rgb]{0.333,0.667,0.333}{#1}}%
\newcommand{\hlkwd}[1]{\textcolor[rgb]{0.737,0.353,0.396}{\textbf{#1}}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at#end#of#kframe{}%
\ifinner\ifhmode%
\def\at#end#of#kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\#totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\#totalrightmargin, so:
\hskip-\linewidth \hskip-\#totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\#totalleftmargin\z# \linewidth\hsize
\#setminipage}}%
{\par\unskip\endMakeFramed%
\at#end#of#kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.
\pdfpageheight\paperheight
\pdfpagewidth\paperwidth
\makeatother
\usepackage{babel}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\section{Section A}
Some text
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{verbatim}
## [1] "Hello World"
\end{verbatim}
\end{kframe}
\end{knitrout}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{verbatim}
## [1] "Where did the explanation of the first graph go?"
\end{verbatim}
\end{kframe}
\end{knitrout}
Explanation of second graph
\end{document}
As you can see, the explanation of the first graph, the subsection heading, and the initial text in subsection A1 do not appear in the output. It just jumps to the output from Chunk 4. The missing text is restored in the output if I either (a) add an '#' character to the end of Chunk 3, or delete the MedSkip after Chunk 3. So it seems there is a bug in there somewhere...
Just let me know if there's anything else that would help!

Short answer: put your cursor just to the left of "Vertical Space" and press return (note that you will not see anything appear to happen). Then compile your document.
Long answer:
You've come across LyX bug http://www.lyx.org/trac/ticket/8875 (which will be fixed in LyX 2.2.0). The problem is that for knitr to work correctly, the # needs to be on a line by itself.
Also, your document is not converted correctly to the LyX 2.1.x format. You can see this if you export your document to .Rnw. You get something weird like:
<<>>=
<<import-external-code,echo=FALSE>>=
read_chunk('mini.R')
#
This does not seem to affect the document output. I'm not sure why. I guess that a second <<>>= overwrites the first. But I think it would be best to clean it up.
The reason for this is that in LyX 2.1.x chunks, the << and >> are handled differently, so you should not have to write them yourself. To fix this, delete << and >> and select the text that remains (which was in-between them before) and go to Insert > Options (or do Alt + A 1, for "first argument").
Can you please open a new LyX ticket at http://www.lyx.org/trac and post your minimal example there? That way we could fix the incorrect conversion.

Related

Disable HTML attribute alignment in Visual Studio Code

VS Code is stacking element attributes when I format HTML files. Is there any way to disable this?
The default setting for this is:
"html.format.wrapAttributes": "auto"
With "auto" meaning:
Wrap attributes only when line length is exceeded.
The line length is defined in a different setting and defaults to 120:
// Maximum amount of characters per line (0 = disable).
"html.format.wrapLineLength": 120
So setting "html.format.wrapLineLength" to 0 should give you the desired behavior.
This worked for me.
In your "Settings.json" file add the line
"prettier.printWidth": 300
How to debug this issue:
Click on HTML
Notice the force option, but also take a look a Wrap Line Length.
Test there to achieve desired results, but...
Test the HTML Formatting First
Open document to edit and right click to format.
Choose the HTML Formatter
Now go back and test each of your other formatters, such as Prettier and TidyHTML etc.
What seemed to work for me was changing the default 120 wrap line length to another value. I tried 0 and still had same problem, but for some odd reason a value of 20 worked. I don't understand why, it just worked.

How to make a figure caption in Rmarkdown?

I am thinking about writing my thesis with rmarkdown and latex. I'm getting the hang of how it all works, however, when I try to add a figure (not an R plot) to the text and render it to pdf, the caption and in-text reference dissappear.
This is the code snippet I use to add a figure:
---
title: "Untitled"
output: pdf_document
---
see figure \ref{fig1}.
![picture \label{fig1}](figure1.png)
This is what knitr creates:
This is what pandoc creates:
Question:
How do I make figure captions and in-text references to those figures in Rmarkdown that will display when rendered to pdf?
OR
How do I tell pandoc what Rmarkdown is so it will render R code and plots?
Please see the documentation of R Markdown for PDF output, and in particular, look for fig_caption. Figure captions are turned off by default in R Markdown, and you have to turn them on (fig_caption: true). You can also find this setting from the gear button on the toolbar of RStudio IDE.
Update: please check https://github.com/yihui/knitr/issues/1063.
Question: How do I make figure captions and in-text references to those figures in Rmarkdown that will display when rendered to pdf?
To get the cross-reference in the PDF produce by LaTeX you need to run LaTeX more than once. Some LaTeX IDE does it for you.
knitr is only running LaTeX once and that is the reason that you only get ??. To confirm that this was the problem I ran
library(knitr)
knitr()
in R that returned
see figure \ref{fig1}.
\begin{figure}[htbp]
\centering
\includegraphics{imagem.jpg}
\caption{picture \label{fig1}}
\end{figure}
which is a valid LaTeX code.
How do I tell pandoc what Rmarkdown is so it will render R code and plots?
Pandoc only understand Markdown (not RMarkdown). First you have to call knitr to generate the Markdown from the RMarkdown and after it call Pandoc to convert the Markdown to LaTeX.
I just found a very useful solution here.
First, include the following chunk:
```{r functions, include=FALSE}
# A function for captioning and referencing images
fig <- local({
i <- 0
ref <- list()
list(
cap=function(refName, text) {
i <<- i + 1
ref[[refName]] <<- i
paste("Figure ", i, ": ", text, sep="")
},
ref=function(refName) {
ref[[refName]]
})
})
```
After, we can add the caption of the figure/table in the figure chunk options like:
```{r, fig.cap=paste("Your caption.")}
See that fig.cap works better with paste.
In Rmarkdown
for markdown figures
![caption \label{labelx}](link_to_figure, or path of figure){figure dimensions}
# how to cite markdown figure
\ref{labelx}
for latex figures
Add following in the figure environment of latex which starts with
\begin{figure}
includegraphics[]{/path to figure}
\label{label}
\end{figure}
# how to cite latex
\ref{label}
for bookdown
add chunk names as label names like
{r label2,echo=F}
# to cite by using bookdown use
\#ref(fig:label2)
similarly for tab we cite table as \#ref(tab:table_label)
For captioner package
add a chunk at the top of rmarkdown document
tab_cap <- captioner(prefix = "table")
fig_cap <- captioner(prefix = "figure")
where prefix is the prefix for cross referencing a figure.
add this in chunk options
{r fig_cap("labelforcaptioner","caption for captioner figure"}
note that fig_cap is similar to fig_cap in chunk code for captioner.
and to cite use
`r fig_cap("label4",display='cite')

How do I move text back to just under the parent level

* Parent
Some text under this level
** Headline below parent
** Another Headline at the same level
I don't want this text to be a headline but be indented same as the text under the parent level without being a headline. Cannot do this.
I just cannot re-indent this text just below the parent level here
* Another top-level headline
Is there any way in org-mode to re-indent plain text back to the same indent level as the plain text just under the parent level but below several headlines under the parent?
I am trying to do something like this:
* A Section
Introductory text.....
** Subsection 1
** Subsection 2
Further Reading
Now, that "Further Reading" is not a headline, I don't want it to be one. However, I cannot "get out of" Subsection 2: Anything I type below it is a part of it. Perhaps I need to structure this some other way such as using lists instead of headlines.
There is no way to do this in org, currently - there is no syntax that ends a subheader to return you to the previous level. But you could add a subsection at the same level - e.g. in your example,
* A Section
Introductory text.....
** Subsection 1
Subsection 1 text
** Subsection 2
Subsection 2 text
** Further Reading
Some further reading
It might be nice if org had some syntax, like **-, that would end a subsection, but I'm not sure how involved a change that would be - probably pretty extensive.

Make org-mode table caption appear below table when exported to LaTeX

I'm producing a document using org-mode which has quite a few tables in it, constructed using the built in table functionality. I've added captions to the tables, but when I export them to LaTeX, rather than the caption appearing below the table, it appears above it. In the manual section on tables and the latex export documentation, there is no mention of any method of changing this, other than fiddling with the LaTeX code manually. As an illustration, the following code snippets show what is generated by the export on an example table with a caption.
#+CAPTION: Results using two methods with different parameter settings.
#+LABEL: tbl:rescomp
| Parameter | Result 1 | Result 2 |
|-----------+----------+----------|
| 0.5 | 0.1 | 0.8 |
| 1 | 0.8 | 0.1 |
Exported:
\begin{table}[htb]
\caption{Results using two methods with different parameter settings.}
\label{tbl:rescomp}
\begin{center}
\begin{tabular}{rrr}
Parameter & Result 1 & Result 2 \\
\hline
0.5 & 0.1 & 0.8 \\
1 & 0.8 & 0.1 \\
\end{tabular}
\end{center}
\end{table}
The problem could be fixed very simply. The caption appears above the table in the document because it is above the table in the code. Moving the caption definition below the tabular section fixes the issue:
\begin{table}[htb]
\begin{center}
\begin{tabular}{rrr}
Parameter & Result 1 & Result 2 \\
\hline
0.5 & 0.1 & 0.8 \\
1 & 0.8 & 0.1 \\
\end{tabular}
\end{center}
\caption{Results using two methods with different parameter settings.}
\label{tbl:rescomp}
\end{table}
Placing the caption definition below the table in the org file is not possible, as it defines the caption for the next table, as described in the manual. Is there any way that I can get org-mode to export the caption below the table produced?
Just updating the answer for Org-mode version 8.3.2 because setting org-export-latex-table-caption-above to nil does nothing now.
I added the next line to my .emacs or init.el file:
(setq org-latex-caption-above nil)
Just as a side note, that variable contains the value (table) by default, which is the one that we are overriding to nil.
In the link posted by N.N., a patch to implement functionality to allow captions to be placed above or below the float was applied. Looking at the org-mode code on github, the default behaviour of Emacs 24.1 is to place captions above the table. To place captions below tables instead, set the org-export-latex-table-caption-above variable to nil:
M-x customize-variable RET org-export-latex-table-caption-above RET nil
or
M-x set-variable RET org-export-latex-table-caption-above RET nil

PDF forms with LaTeX: how to create \TextField of exactly 4in width?

I'm using PDFLaTeX to create forms and ran into a problem with the \TextField macro that defines input fields:
\TextField[width=4in,name=sample]{}
The resulting field is a little wider than 4 inches and I don't understand why. The following example illustrates the problem by resulting in an overfull hbox which gets highlighted by an overfull rule.
\documentclass[a4paper,11pt]{article}
\usepackage[latin1]{inputenc}
\usepackage[pdftex]{hyperref}
\overfullrule3pt
\begin{document}
\noindent \TextField[name=one, width=\hsize]{type here:}
\end{document}
The resulting PDF will show an overfull input field despite having specified exactly the available space as the desired width.
The author of the hyperref package, Heiko Oberdiek, sent me an email and explained why the width is by default greater than specified. Each \TextField is passed through the following macro for layout:
\def\LayoutTextField#1#2{% label, field
#1 #2%
}
Hence, we end up with the label, a space, and the input field. The width parameter only affects the input field. By re-defining the layout, we can ensure that we end up with the desired width as specified:
\def\LayoutTextField#1#2{#2}
This layout would simply drop the label ("type here:") to arrive at an input field of the desired width.