knitr: knitting chunks with parsing errors - r

Is it possible to knit chunks with parsing errors?
I want to produce a document explaining some different types of errors one can find while coding in R, but it seems that I can't knit a chunk with parsing error, even with error = TRUE.
For example, this chunk works fine and it shows the error messages:
```{r sum character, error = TRUE}
"1" + "2"
```
However, this chunk doesn't:
```{r missing parenthesis, error = TRUE}
f <- function(x){
z <- sum(x
#
y <- x + 1
return(x + y + z)
}
```
It gives the error: Error in parse(text = x, srcfile = src).
The idea here would be to show all error messages in the chunk "missing parenthesis", is this possible?

This has become possible since the evaluate package >= v0.8.4 (which is expected to be v0.9 on CRAN in the future). For now, you can install evaluate from Github.

Related

Caption Outside Float Error When Using Stargazer in R Markdown

I try to make a table of summary statistics using R Markdown. Below is my code.
{r new, echo=TRUE, results='asis'}
ws <- t(as.matrix(summary(merged$WS)))
ows <- t(as.matrix(summary(merged$OWS)))
summary1 <- rbind(ws, ows)
rownames(summary1) <- c("Win Shares", "Offensive Win Shares")
stargazer(summary1, title="A Few Summary Statistics on the Data")
When I compile, I get the following error:
! LaTeX Error: \caption outside float.
Error: LaTeX failed to compile stargazers_regressions.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See stargazers_regressions.log for more info.
Execution halted
I have looked up caption outside float in regards to stargazer and haven't seen anything. I have updated all of my packages and even restarted R.
Edit:
Here's a very simple example that still fails:
x <- c(-4, -5)
y <- c(-8, -10)
table_1 <- rbind(x, y)
stargazer(table_1)
It seems that stargazer has an issue with negative numbers. When I changed x to c(4, 5), and y to c(8, 10), the program compiles fine.

R Markdown render fails knit with mlogit, object not found, but code chunks work

I have done a basic search around the site (e.g. R Knit Markdown code chunk: "object not found"), but I don't think I have found anything that fixes my problem, or at least explains why my problem occurs.
There are only a few code chunks in my .rmd which come quite verbatim from https://cran.r-project.org/web/packages/mlogit/vignettes/e1mlogit.html
The first is to load data
rm(list = ls())
library(mlogit)
data("Heating", package = "mlogit")
H <- mlogit.data(Heating, shape = "wide", choice = "depvar", varying = c(3:12))
Then I fit the model, but I use ref_level_var instead of any specific string "gr"
ref_level_var <- "gr"
mc <- mlogit(formula = depvar ~ ic + oc, data = H, reflevel = ref_level_var)
The odd part comes when I try
head(predict(mc, newdata = H))
Now because I require my files to be knit to two different formats (solution via Knit one markdown file to two output files), I use the following knit in my header for the .rmd
knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile, encoding = encoding, output_format = c("html_document", "pdf_document"))})
However, this results in the following error
Error in model.frame.mFormula(formula = depvar ~ ic + oc, data = structure(list(: object 'ref_level_var' not found
Obviously, it seems that somehow ref_level_var is not visible to the knitting session, despite there being a ref_level_var <- "gr" line somewhere. Why does this error occur, and how can I fix it?
Note that the error is very odd, because replacing the whole knit line with output: html_document results in no errors.

non-numeric argument to binary operator (but argument IS numeric indeed)

The dataset contains stats of teams in MLB matches. All of them are numeric.
best <- lm(mlb11$runs ~ mlb11$bat_avg )
summary(best)
plot(mlb11$bat_avg, mlb11$runs) +
abline(best)
qqnorm(resid(best)) +
qqline(resid(best))
class(resid(best))
The qqnorm and qqline just never worked when connected with the "+".
The last line of code returns "numeric", so I think this error message makes no sense. I actually followed every step on a tutorial but could not add the line to the graph. This is so strange!
follow up:
If I removed the "+" between qqline and qqnorm, it returned "Error in int_abline(a = a, b = b, h = h, v = v, untf = untf, ...) : plot.new has not been called yet"
follow up:
when I entered
qqnorm(resid(best)) +
qqline(resid(best))
The right graph did show up in my R window. However, when I tried to knit the rmd file, it stopped on that line and showed the error message. So weird. Would this be a software/system problem?

cbind on ggplotGrob objects fails with "Error in mmm < each : comparison of these types is not implemented"

This appears to be similar to an issue that #baptiste was trying to work around back in 2014. I am revisiting code I wrote back in June that involved creating three ggplotGrobs and combining them with a call to cbind. Now, this code fails with the message: "Error in mmm < each : comparison of these types is not implemented."
I thought that this would be specific to my particular application, but I was able to make a very simple, reproducible example. Even if the cbind is performed on two identical ggplotGrobs, this code still fails.
library(ggplot2)
library(gtable)
# Make some plots
pl1 <- ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point()
pl2 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
geom_point()
# Convert to grobs
pl1_grob <- ggplotGrob(pl1)
pl2_grob <- ggplotGrob(pl2)
# Bind them together -- Error!
combined_grob <- cbind(pl1_grob, pl2_grob)
The error and relevant traceback are here:
> combined_grob <- cbind(pl1_grob, pl2_grob)
Error in mmm < each : comparison of these types is not implemented
> traceback()
8: comp(x_val, y_val)
7: unit(comp(x_val, y_val), x_unit)
6: compare_unit(x$heights, y$heights, pmax)
5: cbind_gtable(x, y, size = size)
4: f(init, x[[i]])
3: Reduce(function(x, y) cbind_gtable(x, y, size = size), gtables)
2: cbind(deparse.level, ...)
1: cbind(pl1_grob, pl2_grob)
This code fails with R-3.4.2 on OS X 10.11.6 with grid_3.4.2, gtable_0.2.0, and ggplot2_2.2.1, AND with R-3.3.2 on Linux (compiled from source on Ubuntu 16.04) with grid_3.3.2, gtable_0.2.0, and ggplot2_2.2.1.
Before making the example above, I noticed that one of the vignettes in the "lemon" package ("gtable_show_lemonade") fails near the very end with the same error upon a cbind of two gtables. I confirmed this error by running the code for this vignette from source, which goes something like:
library(lemon)
edit(vignette('gtable_show_lemonade', package = 'lemon'))
# Then use whichever editor you opened to copy the temporary filename
# of the vignette source, and run this with source()
The compiled vignette (with failed cbind) is here: https://cran.r-project.org/web/packages/lemon/vignettes/gtable_show_lemonade.html
The failure during vignette compilation was obtained using the aforementioned R-3.4.2 instance running on OS X 10.11 (El Capitan).
I would appreciate any help with working around this! Since I would like to use my Mac to generate the figures (better font situation), I'm hoping there is a way I can overload a function to fix this.
UPDATE:
This is "only" a problem if size = 'max', which is the default, is specified (or size = 'min'). I think that I can work around it using size = 'first' or size = 'last', which do not perform the offending height comparisons, but it is certainly not convenient that the default behavior doesn't work (and there are certain situations size = 'max' is useful).
I never managed to get this fixed in gtable so gridExtra has a modified version called gtable_cbind.

Plotting with Knitr in Lyx

I'm trying to plot using Knitr in Lyx. When I run
<<>>=
install.packages("ggplot2")
library(ggplot2)
qplot(y=y, x=1:1000, main = 'Log-Likelihood')
#
I get the error
LaTeX Error: File `figure/unnamed-chunk-6.eps.bb' not found.
I've tried including extensions in the starting brackets, but with no success. How do I get my plot?
Following the first answer, tried this:
Defining function (not that important, just to show how I get y)
<<>>=
exp.loglik <- function(lambda, obs){
xbar = mean(obs)
return(length(obs)*log(lambda)-lambda*xbar)
}
#
Defining y (not that important, but just including to show how y is defined)
<<>>=
y = rep(NA,1000)
for (i in 1:1000){
y[i] = exp.loglik(lambda=i/10000, obs=diet_data$survtime)
}
#
Code that runs and then the error occurs (note that I installed the package in pure R as instructed)
<<warning=FALSE, message=FALSE, echo=FALSE>>=
library(ggplot2)
qplot(y=y, x=1:1000, main = 'Log-Likelihood')
#
Same ERROR: LaTeX Error: File `figure/unnamed-chunk-6.eps.bb' not found.
First, install packages separately, just running install.packages in pure R.
Second, you do not define y.
Here's a minimal example that produces a plot without showing R code, warnings or messages:
<<warning=FALSE, message=FALSE, echo=FALSE>>=
library(ggplot2)
qplot(y=10:1, x=1:10, main = 'Log-Likelihood')
#
Edit:
I am running the following code:
<<>>=
exp.loglik <- function(lambda, obs) {
xbar = mean(obs)
return(length(obs)*log(lambda)-lambda*xbar)
}
#
<<>>=
y = rep(NA,5)
for (i in 1:5) {
y[i] = exp.loglik(lambda=i/5, obs=runif(5))
}
#
<<warning=FALSE, message=FALSE>>=
library(ggplot2)
qplot(y=y, x=1:5, main = 'Log-Likelihood')
#
and I get a picture. Is your code working in clean R? Just re-run it to make sure it is. If everything is ok there, then it might be something with the LATEX/knitr installation.

Resources