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!
Related
I'd like to print a few sentences in a knitr LaTeX doc (.Rnw), but only if some data exists. Those sentences are mostly text, but with some R.
Example:
A chi-squared test of your observed sizes has a p-value of
\Sexpr{format(calculated_chisq$p.value,digits=3,scientific=F)}.
A p-value below 0.05 means you should be concerned that your
groups are broken. The lower the p-value, the more worried you
should be.
I tried a chunk with results='asis', but I think the chunk is interpreted as R.
I tried print() and paste() with R. It's ugly, but it works. However, it puts extra text in that seems to correspond to the R prompt.
Is there a nice way to do this?
This is related, but different. This is the same, but unanswered.
This question is closely related to that question, but not duplicate I think: The accepted answer there translates into an ugly \Sexp monster with a condition inside. The code will be neither nice to read nor to write.
My own answer there is also not applicable because 1) the asis engine does not allow for dynamic elements in the text and 2) because output from the asis gets a gray background color in RNW documents.
I suggest the following solution:
\documentclass{article}
\begin{document}
<<>>=
x <- rnorm(1)
#
The value of $x$ is \Sexpr{x}.
<<echo=FALSE, results = "asis">>=
pattern <- "This will only be displayed if $x$ is positive. The value of $x$ is %.2f."
if (x > 0) cat(sprintf(pattern, x))
#
\end{document}
The conditional output is easy to read and write (pattern) and the dynamic elements are inserted via sprintf.
I have a long .Rnw document which consists mostly of text (typeset in LaTeX) with a few chunks here and there. I have also written a chunk which outputs a specific figure. The figure contains a plot, the values for the plot are currently read from a .csv file and some parameters like colors defined manually within the chunk.
Now I want to have the same figure in a different place in the document, but with different values for the plot and a few other parameters different. Ideally, I would like to include the chunk as a child twice, and pass parameters to it somehow, including the name of the .csv to be used for the plot values. I would hate to copy paste the chunk code with hardcoded parameters, as it is complex enough that potential changes will be difficult to synchronize.
How can I do such "parameterized reuse" of chunks?
update
As requested, a small example
This is saved as include-chunk-reuse.Rnw
<<toReuse, echo=FALSE, result='asis'>>=
l <- 25
#
\newlength{\mylength}
\setlength{\mylength}{\Sexpr{l}pt}
%Omitted: a lot of complicated LaTeX commands
\rule{\mylength}{1pt}
This is the document which is supposed to reuse the chunk. It doesn't even compile, as it complains that the same label is used twice: Error in parse_block(g[-1], g[1], params.src) : duplicate label 'toReuse'
\documentclass{article}
\begin{document}
This is some text. And now comes a 25 pt wide line.
<<first-figure, child='include-chunk-reuse.Rnw'>>=
#
This is some text. The next line is also 25 pt wide. But I would like to call the chunk in a way which makes it 50 pt wide instead.
<<second-figure, child='include-chunk-reuse.Rnw'>>=
#
\end{document}
For the knitr part to work simply leave out the chunk-name in the child document, then you don't have the duplicated label and the knitr part works.
Passing Parameters does not really work as far as I know, but you can just set a global variable before including the child. (For example \Sexpr{l <- 200}
You are still redefining \mylength which is why LaTeX will throw an error, so move the first definition of \mylength from the child to the main document.
The example below demonstrates two ways to reuse and parametrize a chunk.
Reusing Chunks
The mechanism is explained here. Basically, the simplest way to reuse a chunk is to add another empty chunk with the same label. Alternatively, the chunk option ref.label lets a chunk inherit another chunks code.
Both approaches of reusing chunks are largely equivalent – with one exception: figures generated in chunks are saved as chunklabel-i.pdf, where i is the figure index counted by chunk. Therefore, if a chunk is reused by repeating its label, figure i from the second use will overwrite figure i from the first use. This is the reason why I use ref.label (and thus distinct chunk labels) in the example below (otherwise, the points on both plots would be green).
In the example below, I used eval = FALSE in order to prevent evaluation of the masterchunk where it is defined. An alternative would be to externalize the chunk and read it by read_chunk().
Parameterizing Chunks
The two most straightforward options to "pass" parameters to a chunk are
chunk options and
global variables
Also when reusing chunks, each use can set different chunk options. The example below exploits this to set different captions.
As all chunks run in the same environment, setting a variable in an early chunk affects subsequent chunks accessing this variable. In the example below, mycolor is modified this way.
\documentclass{article}
\begin{document}
<<masterchunk, eval = FALSE>>=
plot(1:10, col = mycolor)
#
<<config1>>=
mycolor <- "red"
#
<<use1, ref.label = "masterchunk", fig.cap = "Red dots">>=
#
<<config2>>=
mycolor <- "green"
#
<<use2, ref.label = "masterchunk", fig.cap = "Green dots">>=
#
\end{document}
I am using knitr for a report wherein I have a lot of inline output text, mostly numeric values, using \Sexpr{}. I want to highlight All these inline outputs in my generated pdf.
Example code:
\documentclass[12pt]{article}
\begin{document}
<<echo=FALSE, include=FALSE>>=
N <- 100 # Total
N_f <- 60 # Women
#
There were \Sexpr{N} people in the company, \Sexpr{N_f} women and \Sexpr{N - N_f} men.
\end{document}
Hence, in the output all the number should be highlighted, i.e. with a shaded background (similar to using with \hl{} with the \usepackage{soul}).
It seems to me that the solution would use one of the inline output hooks. Another possibility might be to write a LaTeX function which search all the \Sexpr{...} expressions in the entire document and highlights them in the generated pdf. I am still learning and can not figure out how to implement these.
Thanks for any help or hints.
Note: The knitr page by yihui talks about manipulation of the numeric value (scientific notation, digits after decimal points) which I have got covered.
The output hook inline can be used to style output from \Sexpr{}. This is as simple as
knit_hooks$set(inline = function(x) { sprintf("\\textbf{%s}", x)})
Just define an arbitrary function that takes an argument x and returns the string to be printed. In this example I used \textbf to make the output bold, but this can be extended to any LaTeX commands.
In this answer, Yihui suggests an improvement that still takes the default inline hook into account. This ensures rounding as usually performed by the default hook:
hook_inline <- knit_hooks$get('inline')
knit_hooks$set(inline = function(x) { sprintf("\\textbf{%s}", hook_inline(x))})
WORKING EXAMPLE IN THE END
I want to use knitr to have R code inside LaTeX document, but it doesn't print correctly into PDF when there are non-ascii characters. The situation is similar as in the question user unikum asked in GitHub, but the solution given there helped only partially in my case.
Ideally the printed line(s) would be inside normal text and have suitable LaTeX formatting, especially in cases where the result is simply one line. I have some uses in my mind where example sentences in a research paper would be automatically taken from the data files.
I wrote Rnw file in RStudio (0.98.945), I used XeLaTex for typesetting. I created PDF simply by clicking Compile PDF button in RStudio. I have MacBook Pro with Mavericks. Please let me know if some additional information is needed. I can also switch to other programs (like TeXShop etc.) if that helps.
I'm still learning all these tools, R, knitr and LaTeX, so I apologise if I have missed any obvious solution or misuse some terminology. I tried to combine different solutions from similar problems, like this about Polish characters or this about Hebrew. There are many people writing about bit similar problems, but I still have problems to get it together. I guess this is encoding issue.
Here is my LaTeX preamble:
\documentclass{article}
\usepackage{hyperref}
\usepackage {fontspec}
\setromanfont{Charis SIL}
<<setup, include=FALSE>>=
options(device = function(file, width = 7, height = 7, ...) {
cairo_pdf(tempfile(), width = width, height = height, ...)
})
#
In normal text I can have any possible unicode characters and they appear all correctly in the pdf: мичаа лыддьыны позьӧ, me t'š́uži š́urs e̮kmis-š́o dasɛ͔d voɛ͔ š́ent'a·b das-e̮kmi͔sɛ͔d lunɛ.
I assume this has something to do with encoding.
In my example I scan to R the text file (test.txt) that contains following 10 lines, they are just random word forms in Finnish and Komi:
Серафимлӧн
тшӧктісны
налысь
sivulla
ёрт
дугдыны
sivu-ovi
Esko
Серафим
akkuna
The following code prints the result correctly:
<<test1, echo=FALSE, comment=NA>>=
test <- scan(file="test.txt", what="char", sep="\n")
wordlat <- grep("sivu", test, value=T)
print(wordlat)
#
The result is this:
[1] "sivulla" "sivu-ovi"
But this doesn't:
<<test2, echo=FALSE, comment=NA>>=
test <- scan(file="test.txt", what="char", sep="\n")
wordcyr <- grep("Серафим", test, value=T)
print(wordcyr)
#
What comes out is:
[1] "" ""
I modified marginally the example which was posted to GitHub. I just wanted to have both latin and cyrillic in the labels. As one could expect, adding cairo_pdf to the beginning helped:
<<pie-plot, dev='cairo_pdf'>>=
x <- gl(3, 4, 50, labels=c("Pretty easy!", "Дзик гӧгӧрвотӧм!", "Кувны позьӧ :("))
pie(table(x), main="How difficult is this question")
#
The pie comes out perfectly, but there is clearly still something wrong, because the code above it says:
x<-gl(3,4,50,labels=c("Pretty easy!"," !"," :("))pie(table(x),main="How difficult is this question")
WORKING EXAMPLE:
I see now that I should had paid more attention to give a piece of code one can just copy and run. My apologies for that. So the example below is the same as in my original post, but it can be copied into RStudio and it should make one page PDF which has the problems I described. Sorry for repeating the same, but I though it maybe makes my question more unclear if I start to edit the whole post.
\documentclass{article}
\usepackage {fontspec}
\setromanfont{Charis SIL}
\begin{document}
<<setup, include=FALSE>>=
options(device = function(file, width = 7, height = 7, ...) {
cairo_pdf(tempfile(), width = width, height = height, ...)
})
#
So this comes out fine.
<<test1, echo=FALSE, comment=NA>>=
test1 <- c("Серафимлӧн", "тшӧктісны", "налысь", "sivulla", "ёрт", "дугдыны", "sivu-ovi", "Esko", "Серафим", "akkuna")
wordlat <- grep("sivu", test1, value=T)
print(wordlat)
#
But for some reason this doesn't. How to make it show characters correctly, that's the whole question I posted about.
<<test2, echo=FALSE, comment=NA>>=
test2 <- c("Серафимлӧн", "тшӧктісны", "налысь", "sivulla", "ёрт", "дугдыны", "sivu-ovi", "Esko", "Серафим", "akkuna")
wordcyr <- grep("Сера", test2, value=T)
print(wordcyr)
#
The graphical things come out fine with cairo-package, but only within the graph itself:
<<pie-plot, dev='cairo_pdf'>>=
x <- gl(3, 4, 50, labels=c("Pretty easy!", "Дзик гӧгӧрвотӧм!", "Кувны позьӧ :("))
pie(table(x), main="How difficult is this question")
#
The code above the graph in the PDF has the same problem as in earlier example which contained cyrillic:
c("Pretty easy!"," !"," :("))
\end{document}
Thanks for help!
I am continuing my earlier post here:
Beginner's questions (figures, bibliography) with Sweave/R/LaTeX---my first document
The working code is reproduced here:
\documentclass[a4paper]{article}
\usepackage{Sweave} %%%%%%
\begin{document}
<<echo=TRUE>>=
x <- rnorm(100)
xm <- mean(x)
xm
#
<<echo=FALSE>>=
x <- rnorm(100)
xm <- mean(x)
xm
#
<<echo=TRUE>>=
##### Remove all comments from your data file
test.frame<-read.table(file="apples.d",header=T,sep= "")
names(test.frame)
head(test.frame)
class(test.frame)
#
\begin{figure}[htbp]
\begin{center}
\setkeys{Gin}{width=0.5\textwidth}
<<echo=FALSE,fig=TRUE,width=4,height=4>>=
#### Must tell plot where to get the data from. Could also use test.frame$year
with(test.frame,plot(year,value))
#
\end{center}
\end{figure}
\end{document}
The above runs fine with RStudio (latest) and Tinn-R (latest) and the desired pdf document is produced.
Questions:
If I name the above file as goodex.snw and I run Sweave, I get the file goodex-004.pdf with either Tinn-R or RStudio as the PDF image of the plot. Why the trailing 004? Can this be changed?
Can an EPS file be produced? Is the tool by which Sweave compiles to PDF is only through (PDF)LaTeX and not through the traditional DVI > PS > PDF route?
Just running the command with(test.frame,plot(year,value)) in the R command window generates more values on the y-axis i.e. 15000, 20000, 25000 and 30000. However in the PDF file produced by Sweave by my code at the top of this post, I do not get all the values on the y-axis (only 15000 and 25000). How to control the size of the plot directly in the code so that all necessary y values appear?
Update: the file apples.d contains:
#Number of apples I ate
year value
8 12050 #year 2008
9 15292 #year 2009
10 23907 #year 2010
11 33997 #year 2011
Your example is not reproducible because we don't have the file apples.d, so we can only guess why the plot goes wrong. Please see:
How to make a great R reproducible example?
on how to make a reproducible example.
Please note that Sweave is not a functionality of Rstudio or Tinn-R, it is an R function (Sweave()) that can be run from command line or with arguments from the R executable. This might be helpful to know if you are searching for information.
As for your questions:
The names of plots always have the form FILENAME-CHUNKLABEL.pdf or eps, where the chunk label can be set as option to the Sweave chunk (it's the first argument). If you don't set a chunk name the plots will be enumerated.
You can use eps with the option eps=true. I am pretty sure that by default both eps and pdf are produced though. As for compiling, Sweave does not compile by itself, it creates a .tex file that you can use in whatever way you want. In R 2.14 there is an option to run pdfLaTeX on the produced .tex file automatically,. The way Rstudio and Tinn-R compile is probably by using an pdfLaTeX call after Sweave. You can do it manually if you want to do it differently.
Without a reproducible example we can only guess. What is going wrong? You could set the limits of the plot with the xlim and ylim arguments but that shouldn't be what is going wrong here.
Edit:
In response to edited question with data. First just a tip. This way of giving the data isn't the most useful way of doing it. We can of course reproduce this but it is much easier if you give the data in a way we can run immediately. e.g.:
test.frame<-data.frame(year=8:11, value= c(12050,15292,23907,33991))
As for the plot, you mean the labels on the y axis? This can be changed by omiting axes in the plot call and setting them manually with the axis() function:
with(test.frame,plot(year,value,axes=FALSE))
axis(1)
axis(2,test.frame$value,las=1)
This does look a bit weird if the ticks aren't constantly distributed over the axis though. Better would be:
with(test.frame,plot(year,value,axes=FALSE))
axis(1)
axis(2,seq(10000,35000,by=5000),las=1)