How to include a line containing an error in R markdown - r

I am putting together a small tutorial using R Markdown. I want to include the following:
This is how we create a vector in R:
{r}
x <- c(1,2,3,4,5)
x
We need to use the c() operator to do this; if we don't we get an error as shown below:
{r}
x <- (1,2,3,4,5)
I want to show the error message that R would normally give if I tried to create a vector without the c(), namely
"Error: unexpected ',' in "x <- (1,"
However, when I knit the markdown it stops at the line containing the error. So, how do I deliberately include a line with a mistake in it, in order to demonstrate the error?
Thanks.

Try
```{r, error = TRUE}
x <- (1, 2, 3, 4, 5)
```
An upgrade to knitr changed the default behavior of the error option from TRUE to FALSE. You'll either need to set error = TRUE in each chunk where you want it or use opts_chunk$set(error = TRUE) at the start of your script.

I'm not sure Benjamin's answer will work. Doesn't work for me at least - because the error is a syntax error.
I have two imperfect solutions to this problem. You can 'hack' something that looks right by not evaluating the code with the syntax error, then having a chunk underneath which is evaluated and just shows the error message.
```{r, eval = FALSE}
x <- (1,2,3,4,5)
```
```{r, echo = FALSE}
cat("Error: unexpected \',\' in \'try(x <- (1,\'")
```
Or you can run the code in a different engine. However, it also gives a message saying execution halted that I can't work out how to remove.
```{r, engine='Rscript', error=TRUE}
x <- (1, 2, 3, 4, 5)
```

Related

How to remove display of strange characters in R-Markdown chunk output?

I am getting frequencies from a few rasters and am doing so in R-Markdown. I am using lapply to get the frequencies from the rasters in a list. When I store those frequencies in a list of data.frames, the chunk output displays some unexpected non-numeric characters.
Example rasters:
```{r}
require(raster)
r1 <- setValues(raster(nrows = 10, ncols = 10), sample(1:10, 100, replace = TRUE))
r2 <- setValues(raster(nrows = 10, ncols = 10), sample(1:10, 100, replace = TRUE))
rList <- list(r1, r2)
```
Getting the frequencies:
```{r}
lapply(rList, function(ras) {
data.frame(freq(ras))
})
```
Output from the above chunk:
If I display only the data frame itself, those characters are not displayed:
```{r}
lapply(rList, function(ras) {
data.frame(freq(ras))
})[[2]]
```
The correct values are also shown if do not use data.frame:
```{r}
lapply(rList, function(ras) {
freq(ras)
})
```
I've tried saving the Rmd with UTF-8 encoding and am on RStudio 1.2.5019. Any ideas on how to get the list of data frames to display properly would be appreciated.
Edit: Just a note that the characters do not display in any scenario in the generated html file, only in the specific chunk in the R Notebook file itself.
Edit 2:
The full code and YAML header for the notebook that generates the strange characters is below:
---
title: "R Notebook"
output: html_notebook
---
```{r}
require(raster)
r1 <- setValues(raster(nrows = 10, ncols = 10), sample(1:10, 100, replace = TRUE))
r2 <- setValues(raster(nrows = 10, ncols = 10), sample(1:10, 100, replace = TRUE))
rList <- list(r1, r2)
```
```{r}
lapply(rList, function(ras) {
data.frame(freq(ras))
})
```
```{r}
lapply(rList, function(ras) {
data.frame(freq(ras))
})[[2]]
```
Check out this code is properly showing the output. You can use print
On previewing the html notebook output is not showing any UTF characters
If you want to use the chunk output than you can use
as.data.frame()
I've had this experience before with that same "ÿ" character, but haven't thought about it a lot (Mac RStudio). I have been able to re-run my code and haven't been able to reproduce it on the same chunk, even in the same session.
I do use the formattable package often, and since folks are mentioning the formatting aspect, perhaps that's at play? Although it's hard for me to envision exactly how.
I did find these related items about Pandoc rendering Unicode artifacts on certain character inputs, and about Pandoc converting to UTF-8. Since the workflow involves knitr feeding Pandoc, maybe that's a piece?
https://github.com/jgm/pandoc/issues/844
https://yihui.org/en/2018/11/biggest-regret-knitr/
Can't quite connect the dots, but hope it helps someone else put it together.
I don't remember it happening recently, so potentially one avenue is to update pandoc and knitr (or even RStudio altogether -- I'm on 1.2.5019)?

How do you insert greek symbols into stargazer labels within markdown?

I am trying to insert a greek delta into a covariate label within stargazer. I have tried \Delta but it returns an error about the escape character '\D'. I have attempted with '\', wrapping in '$' and on and on.
What does work is to use the string 'CHG' and then replace all instances of 'CHG' in the html output with &#916.
Sample of R Markdown. Current reference to Delta returning 'delta' not the greek symbol.
I have tried one slash, 2, 3, 4. I have tried wrapping in '${ ... }$
output: html_doc
#```{r setup, include = FALSE, warning = FALSE, comment = FALSE}
library(dplyr)
library(stringr)
library(tidyr)
library(stargazer)
library(knitr)
x <- rnorm(1000)
y <- rnorm(1000)*x
df <- data.frame(x,y)
model1 <- lm(y~x, data = df)
#```{r Perf1.1, echo = FALSE, warning = FALSE, comment = FALSE, message = FALSE, results='asis'}
stargazer(model1, header=FALSE, type = 'html',
dep.var.labels = "\\Delta y")
Backslash is the escape character in R strings. To include it literally you therefore need to … escape it. So, double it up:
dep.var.labels = "\\Delta COGS_{t}",
However, this probably won’t work for HTML output, only for LaTeX output. For HTML, use the corresponding entity, or just use the Unicode character.
For some reason, it seems to work when you surround it with (any?) HTML tag. For example, what worked for me applied to your case would be:
dep.var.labels = "<strong>Δ</strong> COGS_{t}",
dep.var.labels = "<strong>Δ</strong> COGS_{t}
The answer above from #HLRA works for HTML code, not latex code. That is, the output of the "out.html" file can show the symbol of \Delta correctly.
But the latex code generated doesn't work as <strong> is not from the latex language.
I have no idea why but, putting 4 backslashes before any math input worked for me.

How to retain the scientfic format of the numbers while knitting to pdf in rstudio?

The below two code chunks reflects the same output in the R console. But when knit to pdf,it gives me different output. Why?
```{r}
x = 2.22e-16
x
```
```{r}
as.data.frame(x)
```
Output when knitting to pdf:
You can see that, in the data frame, it shows 0 instead of 2.22e-16.
How to correct this?
Note: I use printr package for the nice dataframe and matrix outputs.
setting options(digits = 17) solved the problem but it doesnot seems to be a good solution since it affects all the other chunks if I set it globally.

Inexplicable error when trying to export my R notebook

Getting this error from R Markdown when trying to export my .RMD
"Error in filter(Gastropods, Species == "Cellana") : object 'Species' not found Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> filter"
However, all my plots are coming out successfully. I can clearly see in the data that the species column is there and that Cellana is a species. No spelling errors or anything.
My first 20 or so lines of code are below
###
---
title: " Lab Report 2 - z5016113"
output: html_notebook
i---
#1. Gastropod abundance vs. height on the shore
```{r}
Gastropods <- read.csv(file = "MaroubraZones.csv", header = TRUE)
library(ggplot2, dplyr)
```
```{r}
Gastropods$Zone <- factor(Gastropods$Zone, levels = c("Low", "Mid", "High"))
```
```{r}
Cellana <- filter(Gastropods, Species == "Cellana") ------> This line is causing the error
```
```{r}
ggplot(Cellana, aes(Zone, Abundance)) + geom_boxplot()
```
###
It looks like this might be a bigger issue with DPLYR and filter and I found other posts suggesting they had the same problem and the answer seemed to add dplyr::filter rather than just filter in the command. Link to a similar issue
It might also be worth testing this by filtering out the mollusc of interest before you convert it to a factor?
I have also had similar issues filtering items out and a restart of R fixed the issue.
dplyr::filter has not been found because you haven't loaded dplyr, but since there are other function named filter in other packages, it tries to apply those instead (and fails).
From ?library:
library(package, [...])
[...]
package the name of a package, given as a name or literal
character string, or a character string, depending on whether
character.only is FALSE (default) or TRUE).
This means you can only load one package at a time. Here, you are trying to load both ggplot2 and dplyr in the same call. Only ggplot2 is loaded. The correct way to do this is:
library(dplyr)
library(ggplot2)

Why is ifelse generating print output?

I have some code in my RMarkdown file that I knit:
ifelse(Sys.info()[1]=="Linux",
wdir <- "/path/1",
wdir <- "/path/2")
setwd(wdir)
Except it's supposed to be silent. I've got it in a block with
```{r prepare.data,echo=F,warning=FALSE,message=FALSE,error=FALSE}
I don't want to generate any output from that, yet when I knit, I get this in the output:
## sysname
## "/path/1"
I've tried just that code snip in the console and it is generating that print output.
My Questions are:
1. Why is ifelse printing this output?
2. How can I avoid it?
Thanks!
Try wdir <- ifelse(Sys.info()[1]=="Linux", "/path/1", "/path/2"). The reason the output is printed is that if you don't assign the ifelse output to some variable, it will just print it on the screen. It is like writing a <- 1 + 2 vs 1 + 2.

Resources