Layout of a formula in a bookdown file - r

In my *.Rmd file I'm writing something like this
$\text{Dia}_i = \max_{x, y \in C_i} d(x,y)$
And I was expecting this
but when doing bookdown::render_book(...) and controlling the results in my browser firefox I got
I found that this has something to do with the namelimits (first picture) and nonamelimits (second picture) but unfortunately I have no clue how to change the outcome.
Question: What kind of code chunk I have to add that I can switch between the two notations?
Thanks a lot in advance!
Edit_1
Can I mix these two types?! The goal is to have an inline formula with the desired apperance.
Edit_2
This is my Code - the three dots (...) are the magic/unknown code
And this is my desired output
But sadly I get this
My wish summerized

This should work, following https://stackoverflow.com/a/61979164/13249862:
Add this to your YAML header:
header-includes:
- \newcommand{\argmax}{\mathop{\mathrm{max}}\limits}
Then, you can write both equations:
This $\text{Dia}_i = \argmax_{x, y \in C_i} d(x,y)$, or this $\text{Dia}_i = \max_{x, y \in C_i} d(x,y)$.
Result:

Related

How to suppress unwanted Plot figure object information in Jupyter Notebook

I want to suppress any text output when I run Jupyter Notebook cell. Specifically I output some figures and each is accompanied by something like:
<Figure size 432x288 with 0 Axes>
I have seen that if I put a ; at the end of a line, it should suppress the output, but it is not working in my case.
The code:
for i in tqdm_notebook(range(data.shape[0])):
print('BIN:',i)
fig = plt.figure(figsize=(15,4))
plt.tight_layout()
gs = gridspec.GridSpec(2,1)
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(match[window_begin:window_end],'k')
plt.vlines(i,-np.max(match[window_begin:window_end])*0.05,np.max(match[window_begin:window_end])*1.05,'r',linewidth=4,alpha=0.2)
ax1.set_xlim(0-1,post_bin_match_median[window_begin:window_end].shape[0])
ax1.set_ylim(-np.max(match[window_begin:window_end])*0.05,np.max(match[window_begin:window_end])*1.05)
plt.tick_params(axis='y', which='both', left=True, labelleft=False)
ax1.tick_params(axis='x', which='both', bottom=False, labelbottom=False)
plt.grid()
ax2 = fig.add_subplot(gs[1, 0])
fig.subplots_adjust(hspace=0.0)
ax2.plot(gp_mjds[:],gp_data[i,:],'k')
ax2.errorbar(remain, all[i,:], yerr=all_noise[i], fmt=".k", capsize=0);
ax2.fill_between(gp[:], gp2[i,:] - np.sqrt(gp_var[i,:]), gp2[i,:] + np.sqrt(gp_var[i,:]),color="k", alpha=0.2)
ax2.set_xlim(gp[0],gp[-1])
plot_y_min = np.minimum(np.min(gp2[:,:] - np.sqrt(gp_var[:,:])),np.min(all_profile_residuals[:,:]-y_noise))
plot_y_max = np.maximum(np.max(gp2[:,:] + np.sqrt(gp_var[:,:])), np.max(all[:,:]+y_noise))
ax2.set_ylim(plot_y_min,plot_y_max)
plt.grid()
plt.show()
plt.clf()
plt.close(fig);
The semi-colon would work if the typical output from the last line of the cell is what you are trying to suppress. As succinctly summarized by #kynan here, "The reason this works is because the notebook shows the return value of the last command. By adding ; the last command is "nothing" so there is no return value to show."
However, you have a loop inside a cell generating objects.
The culprit seems to be plt.clf(). Comment out that line or remove it from your code, and it should fix it.
Plus, I'd remove plt.show() as it isn't necessary when plt.clf() is removed, and I am seeing it being in the loop causing fig = plt.figure(figsize=(15,4)) to also show output text like you posted in your issue.
(I'll add for others looking at this later, that it is important have %matplotlib inline or %matplotlib notebook at the start of the cell (or at the start of a cell somewhere above this one.))
A complete guide on how to hide or remove content in Jupyter is available from the official documentation: https://jupyterbook.org/interactive/hiding.html#
For removing the single output line, you can tweak the command lines by adding a _ = [command ] assignment as suggested in this blog: https://www.tutorialguruji.com/python/suppress-output-in-matplotlib/.
The underscore there is a throwaway variable, actually an unidentified variable "when not in interactive mode". See the official Python documentation: https://docs.python.org/3.9/reference/lexical_analysis.html#reserved-classes-of-identifiers

How to prevent Jupyter Notebook from cutting output?

When I print, for some reason Jupyter cuts some text out of the middle of output ( perhaps to make it more readable), but I need to see it.
What are the possible solutions?
Is there any option I can change in Jupyter to prevent if from cutting?
P.S. Sorry can't embed images yet. Use the link, thx.
enter image description here
my_pipeline = make_pipeline(ce.OneHotEncoder(use_cat_names=True),
SimpleImputer(),
XGBRegressor(n_estimators=1000,
learning_rate=0.01,
clf__early_stopping_rounds=10,
clf__eval_set=[(test_X, test_y)],
random_state=45,
verbose=True))
# fitting and predicting
print(my_pipeline.fit(train_X, train_y))
predictions = my_pipeline.predict(test_X)
print("Mean Absolute Error : " + str(mean_absolute_error(predictions,
test_y)))
OUTPUT:
Pipeline(memory=None,
steps=[('onehotencoder', OneHotEncoder(cols=['Neighborhood'], drop_invariant=False,
handle_unknown='impute', impute_missing=True, return_df=True,
use_cat_names=True, verbose=0)), ('simpleimputer', SimpleImputer(copy=True, fill_value=None, missing_values=nan, strategy='mean',
ver... reg_lambda=1, scale_pos_weight=1, seed=None, silent=True,
subsample=1, verbose=True))])
As you see on the OUTPUT by the "ver..." - it is cut. Thx.

\Sexpr{} special LaTeX characters ($, &, %, # etc.) in .Rnw-file

It has something to do with the default inline hook, I realize that and I have tried getting at it (the hook) and also read this thread and Yihui's page about hooks, but I haven't been able to solve my issue. I even tried this suggestion from Sacha Epskamp, but it didn't do this trick in my case.
I'm using \Sexpr and doing something along the lines of \Sexpr{load("meta.data.saved"); meta.data[1,7]} to print a keyword in my report, the problem is that people writing these keywords (people I can't control) are using special LaTeX characters ($, &, %, # etc.) and when they are passed to my .tex file without an \ I'm having a bad time.
I have an .Rnw file with this code,
\documentclass{article}
\begin{document}
Look \Sexpr{foo <- "me&you"; foo} at this.
\end{document}
Thsi creates an .tex file with an illegal LaTeX character. Like this,
<!-- Preamble omitted for this example. -->
\begin{document}
Look me&you at this.
\end{document}
I'm interested to get an output that looks like this,
<!-- Preamble omitted for this example. -->
\begin{document}
Look me\&you at this.
\end{document}
Sorry for the simple question, but can someone help me, and maybe others, getting starting on how to modify the default inline hook for \Sexpr?
The solution provided by #agstudy has shown the basic idea, and here is a more robust version:
hook_inline = knit_hooks$get('inline')
knit_hooks$set(inline = function(x) {
if (is.character(x)) x = knitr:::escape_latex(x)
hook_inline(x)
})
It only modifies the default inline hook when the inline result is character (otherwise just use the default hook). I have an internal function escape_latex() which hopefully escapes all special LaTeX characters correctly.
Hooking works in this case. I customize it like this :
inline_hook <- function(x) {
x <- gsub("\\&", "\\\\&", x)
x <- gsub("\\$", "\\\\$", x)
## good luck for all Latex special character
## $ % _ { } & ~ ^ < > | \
}
knit_hooks$set(inline = inline_hook)
Then
knit(input='report.Rnw')
Will reproduce your report.tex.
PS: I think it is better to not to allow users do what they want.

rstudio code folding like in matlab GUI

I normally use matlab GUI for programming and it has very nice code folding features, such as the following:
%% This is one chunk of code I can fold just because I am using the %% comment format.
matrix = [1 2 3; 4 5 6];
vector = [1 2];
ax = vector*matrix;
%% This is another chunk of code I can fold because I am using the %% comment format.
matrix2 = [7 8 9; 10 11 12];
vector2 = [7 8];
ax2 = vector2*matrix2;
As mentioned in the matlab code, the %% comment will immediatly give the matlab GUI the folding option and a plus/minus sign for unfolding/folding will appear on that line with the comment visible.
Is it anyway to achieve such formatting in rstudio or a good R gui?
I'd like to have the plus/minus feature, and the fact that the first line comment is visible so I can know what's in the folded chunk of code.
Thanks.
Photos of the GUI minus/plus unfolded/folded attached bellow:
When I try the same approach in RStudio, seems that the only option is edit -> folding collapse/expand but it hides the comments, and its not as automatable as the %% feature. In my case is more of a problem because I use X11 so I do not want to have to go to edit -> folding... all the time, but rather automate as in matlab using %%.
Have you seen the code folding section of the RStudio documentation? Everything you ask for is described therein.
To directly quote the most relevant section of the documentation, you can create a code section on any comment line by including at least four trailing dashes (-), equal signs (=), or pound signs (#) automatically creates a code section.
If that wasn't clear enough, maybe we can learn by example:
# Section One ---------------------------------
# Section Two =================================
### Section Three #############################
To illustrate that this actually works further, please examine the following two screenshots. If you are getting something different, I suggest you update RStudio and then follow up directly with the good folks at RStudio:
Expanded:
Collapsed:

Annuity or Angle Operation Symbol in LaTeX

How do I set the symbol for the angle or annuity operation in LaTeX? Specifically, this is the actuarial a angle s = (1-vs)/i.
I've looked at Life's Contingency's Package, various Actuarial Outpost forum threads, and the Comprehensive Symbol List for LaTeX, and combined the best into the following macros:
\DeclareRobustCommand{\lcroof}[1]{
\hbox{\vtop{\vbox{%
\hrule\kern 1pt\hbox{%
$\scriptstyle #1$%
\kern 1pt}}\kern1pt}%
\vrule\kern1pt}}
\DeclareRobustCommand{\angle}[1]{
_{\lcroof{#1}}}
You can then use this macro for the problem's example by typing
$a\angle{s}$
If you need a full set of actuarial symbols, you should use the Life's Contingency's Package lifecon. Using lifecon, you can set the above by typing
$a_{\lcroof{s}}$
For a very comprehensive list of LaTeX symbols, see The Comprehensive LaTeX Symbol List. Worth printing out and keeping under your pillow. Page 95 has some code that may do what you want.
I had the same problem with the actuarial symbol and the subscript/superscript, sooo I made a package to make my life easier and help other.
Plus, I’ve add some shortcut to save time.
The project page and the CTAN.
All you need is the actuarialsymbol package.
At the beginning of the code you have to write
\usepackage{actuarialsymbol}
For the sub/superscript
\actsymb['subscripLeft']['superscriptL']{<middle>}{'subscriptR'}{'superscriptR'}
Example of output:
Example of shortcut for actuarial symbol :
I've been doing some typesetting for a professor of mine and it turns out I needed some help producing the accumulated value of an annuity notation.
I asked this question on the tex stack exchange here
The result that Heiko Oberdiek produced was
\documentclass{article}
\usepackage{siunitx}
\makeatletter
\newcommand*{\NegationLike}[1]{%
\mathop{%
\mathpalette\#NegationLike{#1}%
}%
% A little space is added automatically,
% if a math ord atom follows.
}
\newdimen\BarLineWidth
\newcommand*{\#NegationLike}[2]{%
% #1: math style
% #2: argument
\vbox{%
% The rule thickness of \overline or \underline
% is available in the font dimen register 8
% of the math family 3 of the current size.
\BarLineWidth=%
\the\fontdimen8%
\ifx\displaystyle#1\textfont
\else\ifx\textstyle#1\textfont
\else\ifx\scriptstyle#1\scriptfont
\else\scriptscriptfont
\fi\fi\fi
3\relax
% The rule at the top
\hrule height\BarLineWidth
% Move the box with the vertical line
% as height as the top of the upper line
% to get a better corner.
Which produces:
accumulated value of annuity
\annu
A good list of latex symbols can be found here http://www.ctan.org/tex-archive/info/symbols/comprehensive/symbols-a4.pdf

Resources