tikzDevice not working for basic example - r

Consider the following example:
library(tikzDevice)
tikz("test.tex")
plot(1:10)
dev.off()
An error will be produced once the plot is created, with a lot of code but near the end the error appears:
("C:\ProgramError in getMetricsFromLatex(TeXMetrics, verbose = verbose) :
TeX was unable to calculate metrics for the following string
or character:
m
Common reasons for failure include:
* The string contains a character which is special to LaTeX unless
escaped properly, such as % or $.
* The string makes use of LaTeX commands provided by a package and
the tikzDevice was not told to load the package.
The contents of the LaTeX log of the aborted run have been printed above,
it may contain additional details as to why the metric calculation failed.
In addition: Warning messages:
1: In readLines(texLog) :
incomplete final line found on 'C:\Users\cgmil\AppData\Local\Temp\Rtmp6FouwP/tikzStringWidthCalc.log'
2: In readLines(texLog) :
incomplete final line found on 'C:\Users\cgmil\AppData\Local\Temp\Rtmp6FouwP/tikzStringWidthCalc.log'
What's going on?

A bit late...
You should have a .tex file with the tikz code of your plot in C:\Users\cgmil\AppData\Local\Temp\Rtmp6FouwP/. Just replace the last two lines
\makeatletter
\##end
by
\end{document}
\end{tikzpicture}
Then compile the document. New packages will be installed and it should works.

Related

Warning message in R environment of Sweave file

I keep having the warning message when I execute the following chunk of code. How that could be fixed?
<<fig=TRUE, height=3.5, width=3.5, echo=FALSE, eps=FALSE, results=hide>>=
include_supplement("data.txt")
data <- read.table("data.txt", header=T)
p1<-plot(data[,2], main="XYZ")
p1
#
Warning message:
file stem ‘q.stoch_trend-Copy-001’ is not portable
As the warning message says, it's the file stem q.stoch_trend-Copy-001 on all systems. The . is the problem because some systems might think that this is the end of the prefix and the beginning of the suffix. So I would suggest to replace that with _ or -: q_stoch_trend-Copy-001.

R Markdown error in code when knit to HTML

I am trying to run code chunks in my markdown document. I have an R script that runs all the code that I need without any issues. Then, when I copy and paste the code into the markdown document, the code will run within the chunk, but will fail when trying to knit into an output document (html/pdf).
I had to create a safe.ifelse function to prevent r from converting my dates to a numeric format as discussed here.
The error appears to be with the code:
safe.ifelse = function(cond, yes, no){structure(ifelse(cond, yes, no), class = class(yes))
}
The error message I get is:
Line 121 Error in structure(ifelse(cond,yes,no), class = class(yes)) : could not find function "days" Calls: ... transform.data.frame ->eval->eval-> safe.ifelse-> structure Execution halted
The line of code following my safe.ifelse function is
seminoma1 = transform(seminoma1, recur.date = safe.ifelse(salvage.tx=="Yes",
date.diagnosis + days(pmax(time.rad, time.chemo, na.rm=TRUE)), NA))
Any help would be appreciated. Thanks.
I'm still too new to comment, but the only time I get an error like that is when I forget to define a function/variable or forget to source a package.
Since days() isn't part of R's base package, I think you need to add:
```{r echo = FALSE}
library("lubridate")
```

Knitting returns parse error

In attempting to knit a PDF. I'm calling a script that should return two ggplots by calling the chunk:
```{r, echo=FALSE}
read_chunk('Script.R')
```r
But receive the error
processing file: Preview-24a46368403c.Rmd
Quitting from lines 9-12 (Preview-24a46368403c.Rmd) Error in
parse(text = x, srcfile = src) : attempt to use zero-length
variable name Calls: <Anonymous> ... <Anonymous> -> parse_all ->
parse_all.character -> parse Execution halted
The script on its own runs and returns the two plots, but won't return them when knitted.
Similarly attempted to use source()
But got a similar error
Quitting from lines 7-10 (Preview-24a459ca4c1.Rmd) Error in
file(filename, "r", encoding = encoding) : cannot open the
connection Calls: <Anonymous> ... withCallingHandlers -> withVisible
-> eval -> eval -> source -> file Execution halted
While this does not appear to be a solution for you, this exact same error message appears if the chunk is not ended properly.
I experienced this error and traced it to ending chunk with `` instead of ```. Correcting the syntax of the chunk solved the problem I experienced with the same error message as you.
Are you sure that knitr is running from the directory you think it is? It appears that it is failing to find the file.
use an absolute path, if that fixes it, you've found your problem
once you've done that, you can use opts_knit$set(root.dir = "...") -- don't use setwd(.) if you want it (the cwd) to be maintained.
Knitr's default is the directory of the .Rmd file itself.
It may have to do with the "r" at the end of the triple backquotes demarcating your code chunk. There should be nothing after the triple backquotes, but I think the problem is specifically that the letter is "r".
The issue stems from the fact that R markdown processes backquoted statements starting with r as inline code, meaning it actually runs whatever is between the backquotes.
I had similar issues writing a problem set in an Rmd with this statement, which had backquoted text intended to be monospace but not run as inline code:
Use sapply or map to calculate the probability of a failure rate over r <- seq(.05, .5, .025).
When I knit the document, I got opaque error messages saying I had an improper assignment using <-. It was because instead of just displaying the backquoted statement in monospace, r <- seq(.05, .5, .025) was actually processed as R inline code of <- seq(.05, .5, .025)...thus the improper assignment error. I fixed my error by changing the variable name from r to rate.
The actual text of the error message in your question might refer to whatever follows your code chunk, as the knitting process is probably trying to run that as code. In this case, just removing that stray r at the end of the code chunk should fix the error.
You should use the following similar syntax, I had the same exact issue but got it fixed:
```{r views}
bank.df <- read.csv("C:/Users/User/Desktop/Banks.csv", header = TRUE) #load data
dim(bank.df) # to find dimension of data frame
head(bank.df) # show first six rows
```
the ``` has to be in the end of the line.
In my case was that I finished the code with four comas, not three . Check this and If you finished with four comas too, try to delete one of them.

Error in R. Error in gsub("(?<=\n)(?=.|\n)", continue, x, perl = TRUE) :

I am encountering an error in R that I cannot seem to figure out. I am creating an R markdown document where I read in an a csv table using this code.
iati <- read.csv(file="/filepath/IATI_NGOS.csv",head=TRUE,sep=",")
and then using ggplot2 I create a plot using the following code.
figure_one <- ggplot(iati, aes(iati$reporting.org))+
geom_bar(fill="blue")+
ylab("Total Activities")+
xlab("NGO Reporting Organizations in IATI")+
ggtitle("Total Number of Activities compared to each NGO Reporting Organization in IATI")+
coord_flip()
When I try to call figure_one in the R markdown I get the following error:
Quitting from lines 44-55 (NGO_IATI.Rmd)
Error in gsub("(?<=\n)(?=.|\n)", continue, x, perl = TRUE) :
input string 1 is invalid UTF-8
Calls: <Anonymous> ... paste -> comment_out -> line_prompt -> paste -> gsub
In addition: Warning message:
In grep("\n", message) : input string 1 is invalid in this locale
Execution halted
When I run this code in a regular R script I have absolutely no issues. I have search for some answers but can't figure it out.
Thanks!
I ended solving my issue by just doing a fresh install of R and Rstudio on my local machine. I think the recent update to Yosemite on my local environment created a lot of issues with the TeX plugin I had installed for R markdown.
I get the same question when I knit my rmarkdown document and find **encoding is the cause.
When you use functions like read.csv, fread or read_csv, you will read the column name.
If column names are in other languages, like Chinese, the problem will easily happen.
Or you rmarkdown works on Windows, but the encoding bug happens on Mac, a different environment.
The temporal solution is to rename the column name in English and resave the data files.
Here is the pseudocode in R to show my idea.
library(data.table)
library(tidyverse)
fread('yourfile.csv',encoding = 'UTF-8') %>%
purrr::set_names(c('x1','x2','x3')) %>%
write_excel_csv('yourfile_2.csv')
Here the new file yourfile_2.csv is fine to rmarkdown knit without encoding problems happening.

plot.MCA() not included in Sweave

I don't seem to be having a problem with any other method of including a plot via Sweave. However, plot.mca(), a method from the FactoMineR package seems to not have it's plot pulled through. It does create an Rplot.pdf file - but for whatever reason it's not renamed into "RnwFilename-00X.pdf" and not included in the resulting PDF when you compilePdf() it in RStudio.
Here's a trivial example, try it for yourself.
Note you may have to: install.packages("FactoMineR")
\documentclass[a4paper]{article}
% PREAMBLE
\begin{document}
\begin{center}
<<echo=false,fig=true>>=
library(FactoMineR)
x <- data.frame(
A=sample(letters[1:3],100,rep=T),
B=sample(letters[1:4],100,rep=T),
C=sample(letters[1:3],100,rep=T))
fit.mca <- MCA(x, graph=FALSE)
plot(fit.mca, invisible="ind")
#
\end{center}
\end{document}
Update - more details on the error message:
LaTeX errors:
!pdfTeX error: C:\Program Files (x86)\MiKTeX 2.9\miktex\bin\pdflatex.EXE (file
R:/.../RnwFilename-010.pdf): PDF inclusion: required page do
es not exist <0>
It works for me if I tell plot.MCA not to create a new device:
plot(fit.mca, invisible="ind",new.plot = FALSE)
Editorializing a bit, this seems like sub-optimal behavior for a plotting function, which most users (and other code, clearly) will expect to rely on R's default action to open a new device automatically. A plot function should only open a new device if the user has explicitly told it to (either by calling png, pdf etc or by actually setting new.plot = TRUE). Opinions may differ on this, though.

Resources