Figure numbers generated by Sweave/R and why only (PDF)LaTeX - r

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)

Related

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!

tikz stops drawing into pdf after 20 line segments in plot generated through knitr tikzDevice

Problem
If I try to draw a curve generated through knitr using tikzDevice into .pdf only 20 line segments of that curve are drawn and TeXstudio, through which I do it, just leaves message
running command '"C:\PROGRA~2\MIKTEX~1.9\miktex\bin\pdflatex.exe" "plot2-1.tikz"' had status 1
so I tried to look to /figure folder where I found a .log file where was a line mentioned on which the drawing ended and it was exactly 20 points after the first point of that curve. After that it had the same errors until the end of the file. These errors look like this:
Missing character: There is no X in font nullfont!
where X was the character in the .tikz file which it should have read and drawn.
Example
\documentclass[11pt,a4paper]{article}
\usepackage[czech]{babel}
\begin{document}
<<plot, dev = 'tikz', echo = FALSE, cache = FALSE, fig.width = 7, fig.height = 5>>=
curve(sin, 0, 2*pi)
#
\end{document}
If I omit the dev = 'tikz' in chunk options, it works. I've also tried many other things which had no effect on this issue so I deduce there's something wrong with tikzDevice package in R.
my tikzDevice has version 0.7.0.
I can tell more information about my setup if you want. Just ask.
Question
What should I do to fix this?
Remark
This is a duplicate of this question I posted on TeX.SE. I don't really know where it belongs more...

export all the content of r script into pdf

I would want to export all the content of r script into pdf. Could it be possible?
I used these commands export, but what I see I just exported graphics
pdf(file = "example.pdf")
dev.off()
Thank you!
setwd("C:/Users/Prat/Desktop/c")
> dir()
[1] "script.R"
> knitr::stitch('script.r')
output file: script.tex
In my folder doesn't appears a script.pdf else a script.tex and a folder with the pictures in pdf
You can do this with the knitr package. Here's a workflow:
Save your script as a file (e.g., myscript.r)
Then run knitr::stitch('myscript.r')
The resulting PDF will be saved locally as myscript.pdf. You can use browseURL('myscript.pdf') to view it.
You can generate html file by using,
knitr::stitch_rhtml('filename.r')
As .tex file is not easily readable but html files can view in any browser easily.
For everyone who is looking for an easy and fast solution, I would propose using the function capture.output (https://www.rdocumentation.org/packages/utils/versions/3.6.2/topics/capture.output) from utils.
One only needs to 1.) capture what ever command one wants to run and assign it to a variable and 2.) then print that variable. Images can be printed along the way as you can see. The example on the webpage I linked above does not use markdown.
Here my example with markdown (this is really all one needs):
```{r, echo = F}
# fake data-set
x = rnorm(50, mean = 3.3, sd=1)
y = rnorm(50, mean = 3.1, sd=0.9)
z = rnorm(50, mean = 3.2, sd=1.1)
# create dataframe
df <- data.frame(x, y, z)
# adding a graphic
plot(df$x, df$y)
# create a model as example
linearMod <- lm(y ~ x + z, data=df)
# all one needs to capture the output!!:
bla <- capture.output(summary(linearMod))
print(bla)
```
Remark: if one also wants to print the command, that is also easy. Just replace "echo = F" with "warning = F" or remove the text altogether if you also wanna have the warnings printed, in case there are any.
I was having the same issue, but I realized I was working in R 4.1 and ignored the warning that knitr was created using R 4.2. However after updating my R version, I was also just getting a .tex file but when I read the .log file I found the error "sh: pdflatex: command not found."
I used this suggestion with success:
Have you installed a LaTeX distribution in your system? For rmarkdown,
tinytex is recommended, you would need to install the R package and
then the TinyTex distribution.
install.packages('tinytex')
tinytex::install_tinytex()
Make sure you not only install the package but also run that second command tinytex::install_tinytex() as I made that mistake also before finally getting the program to create a pdf file.
Here is the link to the site where I found this method.
https://community.rstudio.com/t/knitting-error-pdflatex-command-not-found/139965/3
Please use the below set of codes (you need to modify it according to your dataset/data-frame name).
library(gridExtra)
library(datasets)
setwd("D:\\Downloads\\R Work\\")
data("mtcars") # Write your dataframe name that you want to print in pdf
pdf("data_in_pdf.pdf", height = 11, width = 8.5)
grid.table(mtcars)
dev.off()
Thanks.

How to join a PDF files in R?

I've an R program that outputs a booklet of graphics as a PDF file onto the local server. There's a separate PDF file, an introduction piece, not written in R, that I would like to join my output to.
I can complete this in Adobe and R-bloggers has the process here, both of which involve joining the files by hand, as it were:
http://www.r-bloggers.com/splitting-and-combining-r-pdf-graphics/
But what I'd really prefer to do is just run my code and have the files join. I wasn't able to find similar posts while searching for "[R] Pdf" and "join", "merge", "import pdf", etc..
My intent is to run the code for a different ID number ("Physician") each time. The report will save as a PDF titled by ID number on the server, and the same addendum would be joined to each document.
Here's the current code creating the R report.
Physician<- 1
#creates handle for file name and location using ID
Jumanji<- paste ("X:\\Feedback_ID_", Physician, ".pdf", sep="")
#PDF graphics device on, using file handle
pdf(file=Jumanji,8.5, 11)
Several plots for this ID occur here and then the PDF is completed with dev.off().
dev.off()
I think I need to pull the outside document into R and reference it in between the opening and closing, but I haven't been successful here.
To do this in R, follow #cbeleites' suggestion (who, I think, is rightly suggesting you move your whole workflow to knitr) to do just this bit in Sweave/knitr. knit the following to pdf, where "test.pdf" is your report that you're appending to, and you'll get the result you want:
\documentclass{article}
\usepackage{pdfpages}
\begin{document}
\includepdf{test.pdf} % your other document
<<echo=FALSE>>=
x <- rnorm(100)
hist(x)
# or whatever you need to do to get your plot
#
\end{document}
Also, the post you link to seems crazy because it's easy to combine plots into a single pdf in R (in fact it's the default option). Simply leave the pdf device open with its parameter onefile=TRUE (the default).
x <- rnorm(100)
y <- rnorm(100)
pdf("test.pdf")
hist(x)
hist(y)
dev.off()
Plots will automatically get paginated.
You can also consider something like :
library(qpdf)
path_PDF1 <- "C:/1.pdf"
path_PDF2 <- "C:/2.pdf"
pdf_combine(input = c(path_PDF1, path_PDF2), output = "C:/merged.pdf")

Plot in nowhere

I am using the function plotMDS() of package limma that makes a plot by the simple plot() format of R, and also returns the position of the points on the plot as output. I want to use the output of plotMDS() to produce my own beautiful plot.
Is there any way to run plotMDS() without having it's plot really generated? The reason I ask so is that I have already casted the output to a PDF file and I don't want the original plot of the plotMDS() to be there!
Thanks #BenBolker, it can be done like this:
pdf("Some file")
...
dev.new() # Putting new plots to nowhere
mds <- plotMDS(data)
dev.off() # Restoring new plots to the PDF file
plot(...) # Making the desired plot using mds
...
dev.off() # Closing PDF file
Looking at your answer it seems like this might be a reasonable alternative:
mds <- plotMDS(data)
pdf("Some file")
...
plot(...) # Making the desired plot using mds
...
dev.off() # Closing PDF file
I don't know exactly what you're doing but if you're interested in reproducible documents then you could also use the knitr package to create your output. It would be very easy to suppress a single plot and then plot later using knitr.

Resources