RStudio: Code sections and compiled notebooks - r

I really like RStudio's code sections because they help me keep my code organized and makes navigation very easy. So, the code/comment line for code sections look like this (the key for RStudio to recognize the code section is that the comment should end with four or more #, - or =).
# Section One ---------------------------------
# Section Two =================================
### Section Three #############################
Now, I also find very useful "Compiling Notebooks from R Scripts" because you can produce reports directly from your script (which I find much more comfortable working with) without having to write an RMarkdown document. You simply have to use roxygen2-style comments (using #' as prefix) and they will be converted to markdown and/or use #+ or #- prefixes to control RMarkdown chunk options.
Now, I want the best of both worlds but I cannot find a way to get it. I want to have code sections (recognizable for RStudio) in the report (with the proper markdown for headings #, but without the extra #### at the end of the line). Seems like an impossible task to me. If I use #' prefix, I get the section in the report but RStudio does not recognize it as a code section. If I do not use roxygen2-style comments, RStudio recognizes the code section but it does not appear in the report (ok, it appears but as an ugly comment in the formatted code). The best solution I have found so far is to use the #+ prefix and simulate a code chunk label. That way I can get RStudio to recognize it as a code section, and it does not appear in the report as an ugly comment.
Any ideas on how to do this better?

Related

R/exams: how to select different font type for pdfs

HI am pretty new to coding with R/LaTeX and currently trying to figure out how to set up exams using R/exams. While I have already managed to create the exercises themselves, I now want to save them as pdfs using exams2pdf.
However, I would like to use a different font than the one used by default. Does anyone know whether this is possible and, if so, how I have to add this to my code?
Is it also possible to change the "Header", where it says "1. Problem" to something else/remove it?
Thanks a lot for your help.
Overview
In exams2pdf() there is the template = argument with which you can specify a master LaTeX template into which the individual exercises are embedded. By providing your own template you can change any aspect you like: fonts, page formatting, intro text, whether or not questions/solutions are shown, etc.
Below I give a rather detailed overview so that this post is also useful for other R/exams users that want to modify other aspects of the template in exams2pdf().
Getting started
To get started I would recommend to go to a suitable working directory and then set up exams_skeleton() there, e.g.,
exams_skeleton(dir = ".", writer = "exams2pdf", markup = "markdown")
which copies all of the .Rmd exercises (due to the markup = "markdown" specification) available in R/exams to an exercises/ folder, along with all available LaTeX templates to the templates/ folder, and sets up two demo .R scripts: demo-all.R and demo-pdf.R. You can look at these, especially the latter, and play around with the examples provided there.
Vignette
More details and background information are then provided in a package vignette: vignette("exams", package = "exams"), especially Section 3.
The master LaTeX template
For doing the concrete adaptations you ask for, I would start by modifying the plain.tex template in the templates/ directory. The "factory-fresh" default content is:
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{a4wide,color,Sweave,url,amsmath,booktabs,longtable,eurosym,amssymb}
\newenvironment{question}{\item \textbf{Problem}\newline}{}
\newenvironment{solution}{\textbf{Solution}\newline}{}
\newenvironment{answerlist}{\renewcommand{\labelenumii}{(\alph{enumii})}\begin{enumerate}}{\end{enumerate}}
\providecommand{\tightlist}{\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setkeys{Gin}{keepaspectratio}
\begin{document}
\begin{enumerate}
%% \exinput{exercises}
\end{enumerate}
\end{document}
Changing question and solution formatting
For example, you could decide to only show the question but not the solution by modifying the {question} and {solution} environments above to:
\usepackage{verbatim}
\newenvironment{question}{\item}{}
\newenvironment{solution}{\comment}{\endcomment}
Changing the answer list formatting
Then you could modify the answerlist from (a), (b), ... to A., B., by modifying the {answerlist} environment:
\newenvironment{answerlist}{\renewcommand{\labelenumii}{\Alph{enumii}.}\begin{enumerate}}{\end{enumerate}}
Changing the font
And finally you could modify the default font to Lato, say, by loading the {lato} package and using a dark gray (rather than the default black) font color. To do so insert before the \begin{document} line:
\usepackage[default]{lato}
\definecolor{darkgray}{rgb}{0.23,0.23,0.23}
\color{darkgray}
Run exams2pdf() with new template
And then to see the result, run:
exams2pdf("swisscapital.Rmd", edir = "exercises/", template = "templates/plain.tex")

How to create exam sheets with solutions in a non-English language with R exams

In order to create the exam sheets without solution, everything works fine with exams2nops (apart from the logo which is not taken for some reason). I can add the name of the institution, change the title, and setup a non-English language and the date. But if I want to create examsheets with the solutions, then, if I understand correctly, I cannot use anymore exams2nops, but I have to use exams2pdf with template="solution" which does not take into account the institution, the date, the language, nor the title.
Any help?
You are correct that exams2nops() does not provide a version of the PDF with the {solution} environment and the complete answer text. The nops_eval() only provides a HTML report with the correct boxes that needed to be checked.
So to produce a PDF as desired you can run exams2pdf(...) or exams2pdf(..., type = "solution") after setting the same random seed that you set before running exams2nops(). If you want to modify anything like layout/logo/language/etc. in exams2pdf() you have full flexibility but need to do the work yourself. That is you need to come up with a LaTeX template file that looks the way you want. As a starting point you can take solution.tex from the package. The easiest way to get all templates shipped with the package is to run exams_skeleton() and then look at the templates folder.
Background info: exams2nops() also just calls exams2pdf() internally after setting up a suitable LaTeX template file based on the arguments specified by the user.

Indenting code within .R script without using a function

I am new to R, and despite searching the forums I have been unable to find a solution to indenting code within both the Source window and Document Outline (Ctrl+Shift+O).
An example is shown below.
Ideally, I would want the code to function as below when pressing Alt+O
This function does seem to be implemented in some fashion as you get the indented code with functions but this is less than ideal.
# Section 1 -----------------------------------------------------------
function(x) {
# Section 1A ===========================================================
}
Has anyone found a work-around to implement this?
Not a fix but a workaround:
Any whitespace after a "." is included in the heading, so a "." followed by a tab or space can be used to create indented headers preceded by a ".".
# Section title ---------------------------------------------------------------
# . Subsection A --------------------------------------------------------------
# . . A.1 ---------------------------------------------------------------------
Would still be nice to see this implemented the way it is in R markdown, but in the mean time might make it easier to navigate scripts using sub-headers.
Screenshot of example script using dot-tab to indent headers
For what it's worth, this sort of nested indent is implemented for Markdown sections (for e.g. R Markdown documents), e.g.
However, this sort of nested is not implemented for sections in plain R scripts. You might consider filing this as a feature request for the RStudio team.
Thanks #Foztarz I posted this as an issue about a year ago on the GitHub. They claimed it was a worthy enhancement but they keep pushing it to the next version of RStudio lol. My work-around was similar. I used Alt codes to insert symbols I found a bit more visually appealing over .
# ▬ Section A ------
# ▐ ▬ Section A.1-----------
Here's what it looks like inside RStudio
Two additions:
Box-drawing characters look much better than the characters mentioned in https://stackoverflow.com/a/63812437/13776976 #Patricks answer
From RStudio 1.4 on, you can indicate sub-sections by additional '#' at the start of the line, see RStudio How To Article

How to disable spell checking in code regions in RMD files (Markdown, knitr, R)

I am using the Vim-R-plugin to edit files containing markdown and R-code blocks such that the files can be complied using knitr. The filetype is: RMD. I have enabled spell checking. How can I disable the spell checking within the code blocks?
Spell checking is attached to certain syntax groups. Find the :syn region that covers the R code blocks, and append / edit in contains=#NoSpell.
Instead of trying to get the #NoSpell working by region, my approach is to toggle between languages.
I work in three languages which are set up to toggle with a function key where I include "nospell". This makes turning spellchecking on and off as easy as pressingt F7. When coding and writing nospell is turned on, when finalizing the edits I toggle to the appropriate language.
In fact, I find spellchecks in my code to be a plus. I make mistakes in the comment sections too, sometimes even in variable names/plot lables etc. This way you have a quick last check of all language items that are going to be visible .
I got this to work on OS X by editing the ~/.vim/syntax/R.vim and doing a search and replace of all instances of #Spell to #NoSpell. Then restarting vim. All the red underscores were gone from the code chunks but were still in the rest of the the rmarkdown.
Interestingly this has not effected the spell checking in pure R documents that have a .R extension, so I having thought I understood what I was doing perhaps I have to admit I don't fully. But at least it has turned off spell checking of the code chunks in rmarkdown (Rmd) documents while leaving it still working elsewhere in the document.

Linking/importing externalized source code in org-mode

This paper inspired me to check out Emac's org-mode a bit and currently I try to assess what's more suitable for writing my documents: knitr/Sweave (I'm mainly using R to do my programming) or org-mode.
What I really like about knitr is the option to externalize the actual source (watch out: the declaration of labels/names in the R script seems to have changed from ## ---- label ------- to ## #knitr label; see ?read_chunk) and "link" them to the actual literate programming/reproducible research document (as opposed to actually writing the code in that very document):
"Import" with
<<import-external, cache=FALSE>>=
read_chunk('foo-bar.R') # has label/name 'foo-bar'
#
and "re-use" by referencing the respective labels with
<<foo-bar>>=
#
Question
Is this also possible in org-mode or am I bound to putting the actual code into the .org document?
I found this, but I did not find any specific notion of linking/importing external source code files and be able to execute them by having the linked code inside
#+BEGIN_SRC R
<linked code>
#+END_SRC
Background
I do see that this approach might contrast the general paradigm of literate programing to some extend. But I like to work in a somewhat "atomic" style and thus it feels more natural to me to keep the files separated at first and then mash everything together dynamically.
Would named code blocks help?
#+NAME: foo-bar
#+BEGIN_SRC R
source(foo-bar.R)
#+END_SRC
And then evaluate (i.e. load) the code when you actually need it:
#+CALL: foo-bar()
See manual for more details.

Resources