Assign sage variable values into R objects via sagetex and Sweave - r

I am writing a short Sweave document that outputs into a Beamer presentation, in which I am using the sagetex package to solve an equation for two parameters in the beta binomial distribution, and I need to assign the parameter values into the R session so I can do additional processing on those values. The following code excerpt shows how I am interacting with sage:
<<echo=false,results=hide>>=
mean.raw <- c(5, 3.5, 2)
theta <- 0.5
var.raw <- mean.raw + ((mean.raw^2)/theta)
#
\begin{frame}[fragile]
\frametitle{Test of Sage 2}
\begin{sagesilent}
var('a1, b1, a2, b2, a3, b3')
eqn1 = [1000*a1/(a1+b1)==\Sexpr{mean.raw[1]}, ((1000*a1*b1)*(1000+a1+b1))/((a1+b1)^2*(a1+b1+1))==\Sexpr{var.raw[1]}]
eqn2 = [1000*a2/(a2+b2)==\Sexpr{mean.raw[2]}, ((1000*a2*b2)*(1000+a2+b2))/((a2+b2)^2*(a2+b2+1))==\Sexpr{var.raw[2]}]
eqn3 = [1000*a3/(a3+b3)==\Sexpr{mean.raw[3]}, ((1000*a3*b3)*(1000+a3+b3))/((a3+b3)^2*(a3+b3+1))==\Sexpr{var.raw[3]}]
s1 = solve(eqn1, a1,b1)
s2 = solve(eqn2, a2,b2)
s3 = solve(eqn3, a3,b3)
\end{sagesilent}
Solutions of Beta Binomial Parameters:
\begin{itemize}
\item $\sage{s1[0]}$
\item $\sage{s2[0]}$
\item $\sage{s3[0]}$
\end{itemize}
\end{frame}
Everything compiles just fine, and in that slide I am able to see the solutions to the three equations respective parameters in that itemized list (for example the first item in the itemized list from that beamer slide is outputted as [a1=(328/667), b1=(65272/667)] (I am not able to post an image of the beamer slide but I hope you get the idea).
I would like to save the parameter values a1,b1,a2,b2,a3,b3 into R objects so that I can use them in simulations. I cannot find any documentation in the sagetex package on how to save output from sage commands into variables for use with other programs (in this case R). Any suggestions on how to get these values into R?

Wow, you are really mixing two worlds ;)
The only idea I can give you is the "solution_dict=True" parameter for the solve command. Then you get a Python dictionary whicht might help you to just output the value. But I have no idea what exactly Sweave does and when which step of the process rewrites what.
In general, it might be better if you would write it in sagetex only and call R via the rpy2 Python wrapper. But that might be too much work for you - maybe just for one slide and then stitch them together via some pdf-merging?

Related

Creation of especialized \Sexpr function version

I'm using the exams package to generate some exams (engineering). My source files are in Rnw format so the underlying engine is Sweave.
In R side, I'm using units package (to check dimensionality correctness) and I've created a function (called units2tex) to convert a magnitude from units to LaTeX equivalent. So, when I calculate a variable, I have to create a copy for LaTeX:
<<>>=
R = set_units(1,ohm)
I = set_units(1,A)
V = R*I
R_tex = units2tex(R)
I_tex = units2tex(I)
#V_tex = units2tex(V)
#
For $R = \Sexpr{R_tex}$, the answer is \Sexpr{units2tex(V)}.
In both cases (to print R and V) I have to explicitly call units2tex function somewhere. It's is a lot of typing (more to type, more places to be wrong) because there are a lot of steps and intermediate temporal values.
Is it possible to easily create versions of \Sexpr with automatic function calls?
More concretely:
Is is possible to create \SexprT{V} to function like \Sexpr{units2tex(V)}?
Is is possible to create \SexprT{V,digits=2} (or similar) to function like \Sexpr{units2tex(V,digits=2)}?
In both cases without losing the use of original \Sexpr.
My current options and its cons:
Explicitly call to units2tex(...) and duplicate variables (units version and LaTeX version). It is my current approach. A lot to typing, prone to forget conversions or generate conversions that they are not used latter.
use very short function names: \Sexpr{t(V)}. Difficult to remember the meaning of each translation function. Pollution of the namespace. I still remember last time I use a c function (after a and b ones) and break original c function.
Use some kind of preprocessor and made the changes. As I said before, all ecosystem is to work with exams package. This package executes Sweave in the background, I do not want to alter the pipeline of the files to generate the tests. I would write a *.Rnw2 file and have to create a script in ¿sed? ¿R?, read files, modify values and generate the *.Rnw file and then call exams2pdf functions... There is problems if I forgot to update Rnw exams files. I'd use a Makefile to coordinate, but I have to switch between a terminal and Rstudio... This option is, maybe the best (after the creation of \Sexpr versions) but the solution obscures the pipeline and difficult quick questions generation to check them.
So, the best approach is: Is it possible to create variations of \Sexpr?
Full example: file: "question.Rnw"
\usepackage[utf8]{inputenc}
\usepackage[OT1]{fontenc}
<<echo=FALSE, results=hide>>=
library(units)
units2tex <- function(x) {
# this function is not important here. Simplified version the original version much complex
paste0(x,deparse_unit(x))
}
#
\begin{question}
<<echo=FALSE, results=hide>>=
In <- set_units(1e-3,A)
Pn <- set_units(sample(c(2,1,0.5,0.25,0.125),1),W)
In_tex <- units2tex(In)
Pn_tex <- units2tex(Pn)
#
A resistor nah nah nah current $I_n=\Sexpr{In_tex}$ nah, nah, nah $P_n=\Sexpr{Pn_tex}$
What is V?
<<echo=FALSE, results=hide>>=
Vn <- set_units(Pn/In,V)
Vn_tex <- units2tex(Vn)
#
\begin{answerlist}
\item $V = \Sexpr{Vn_tex}$
\item $V = \Sexpr{Pn_tex}$
\item $V = \Sexpr{In_tex}$
\end{answerlist}
\end{question}
\begin{solution}
To calculate $V$, we do $V= P_n/I_n = \frac{\Sexpr{Pn_tex}}{\Sexpr{In_tex}} = \Sexpr{Vn_tex}$
\begin{answerlist}
\item Ok
\item Bad
\item Wrong
\end{answerlist}
\end{solution}
\exname{question1}
\extype{schoice}
\exsolution{100}
\exshuffle{TRUE}
And to compile:
library(exams)
exams2html(c("question1.Rnw"), encoding="utf-8",template='plain8.html',mathjax = TRUE)
In Rnw exercises the content of \Sexpr{} is turned into character by explicitly calling as.character() on it. As this is a generic function you could easily define your own method, say,
as.character.units <- function(x, ...) units2tex(x, ...)
and then simply using \Sexpr{V} will automatically call your units2tex() function behind the scenes.
Note that the same does not work for Rmd exercises. So i you want to mix Rnw and Rmd exercises, then using a shortcut function name such as the following might be better:
u2t <- function(x, ...) units2tex(x, ...)
This would then need to be called as \Sexpr{u2t(V)} and `r u2t(V)`, respectively.
To reduce the pollution namespace:
a <- list(t=function(x){units2tex(x)},d=function(x){units2tex(x,digits=2)})
and later \Sexpr{a$t(V)}
It's almost shorter than \Sexpr{V_tex} but I do not have to define V_tex.

`bookdown`/`rmarkdown`/`knitr`: Non-code sequential processing howto?

Programatically my bookdown project proceeds as follows:
Reading in raw data - produces all kind of stats.
Data preprocessing (logarithmization, normalization, imputation) - produces various plots for monitoring the population-level defects incurred.
PCA for analysis QC - produces plots for PCA and loadings-dominating data points.
Differential expression analysis - produces volcano plots and plots characterizing prominent differentially expressed features.
Overrepresentation analysis of the differentially expressed features from 4. in various biological ontology systems - produces example bar plots for enriched categories.
I have analysis and narrative nicely integrated using bookdown, enabling efficient on fly discarding of temporary (sizable) data sets/ggplot2 objects (pre/post transformation data etc.).
HOWEVER: The target audience is mostly/only interested in 4. & 5., leading me to the aspired to following structure:
4., 5., Appendix(1., 2., 3.)
Is there any other way but precomputing 1.-5. and then revisiting in the targeted order - I would prefer to avoid accumulating all those ggplot2 objects in memory if at all possible.
You could do the following:
Split steps 1-3 and 4-5 into two speparate *.Rmd files, say 123.Rmd and 45.Rmd.
Add a code chunk to the beginning of 45.md that knits 123.Rmd to 123.md:
```{r knit123, include = FALSE}
knitr::knit("123.Rmd", output = "123.md")
```
This will generate the output of steps 1-3 in Markdown and make all the objects created thereby available to steps 4-5.
Add a code chunk to the end of 45.Rmd that reads 123.md prints its content:
```{r include123, results = "asis"}
cat(readLines("123.md"), sep = "\n")
```
The results = "asis" will prevent any further processing as it is already valid Markdown.
Knit 45.Rmd to whatever target format you want.
edit (1):
TL;DR: Instead of storing the object from steps 1-3 in memory throughout steps 4-5 in order to print them afterwards, print them first and store the results on disk.
edit (2):
Since you explicitely mentioned bookdown: I would not be surprised if there was a YAML option to include a Markdown file at the end of the knitting process (something like include-after: 123.md); but I don't know for sure from the top of my head and I'm too lazy to look it up myself. ;-)

Can you make inline chunks in knitr evaluate last?

I am using knitr to write a manuscript.
I am using inline chunks to make sure the text matches my actual data.
For example "I performed regression on \rinline{nrow(df)} data points."
However, this information is needed in the abstract and other early parts of the text, while df is created by code that is next to the methods section that explains how it is created.
Can I force all inline chunks to evaluate last?
To be clear here is a markdown example.
Abstract
---------
My study is really interesting.
I performed regression on `r nrow(df)` data points.
Methods
--------
I used simulated data drawn from a normal distribution.
```{r data}
df <- data.frame(x = rnorm(10), y = rnorm(10))
```
The second sentence in the abstract should read "I performed regression on 10 data points."
In writing the MRE I discovered the answer.
If you knit the document in an R session, the variables will be saved to the global namespace.
Knitting the document a second time will fill in the inline chunks.
I didn't get any errors in the first knit.
So you do need to check that the final document does contain all the inline values.

inline Latex code inside knitr R block

I am looking for a way to put inline latex code into a R code chunk in Knitr.
Here is my example code from the knitr example site :
\documentclass{article}
\begin{document}
Example text outside R code here; we know the value of pi is \Sexpr{pi}.
<<my-label, echo=FALSE, eval=TRUE>>=
set.seed(1213) # for reproducibility
x = cumsum(rnorm(100))
m <- mean(x) # mean of x
print(m)
cat(m)
plot(x, type = 'l') # Brownian motion
#
\textit{Mean is :} \textbf{\Sexpr{m}}
\end{document}
For something simple like this is I could use result='asis' but for a more complicated piece of code, where you want to periodically write the result out to the document, (especially you have complex ggplot graphs), that solution does not work very well.
In the given example, I have 3 queries :
How would I use inline latex code for the output from line 8, in case I wanted to color, bold etc. that text.
Can one eliminate the grey box that appears when we use the cat or print command.
Can the numbering which appears with the print command, which is eliminated with the cat command be eliminated for the print command as well, since print has many variants in many packages for data frames data tables etc. and might be more commonly used to print a portion of data.
In summary, I am mainly looking for the inverse of line 12 in the code.
I have also unsuccessfully tried knit_print with printr, and asis_output, in lieu of print. Although I may have been incorrectly using them.
Thanks!

Is it possible to to export from reporttools?

I am using tableNominal{reporttools} to produce frequency tables. The way I understand it, tableNominal() produces latex code which has to be copied and pasted onto a text file and then saved as .tex. But is it possible to simple export the table produced as can be done in print(xtable(table), file="path/outfile.tex"))?
You may be able to use either latex or latexTranslate from the "Hmisc" package for this purpose. If you have the necessary program infrastructure the output gets sent to your TeX engine. (You may be able to improve the level of our answers by adding specific examples.)
Looks like that function does not return a character vector, so you need to use a strategy to capture the output from cat(). Using the example in the help page:
capture.output( TN <- tableNominal(vars = vars, weights = weights, group = group,
cap = "Table of nominal variables.", lab = "tab: nominal") ,
file="outfile.tex")

Resources