R Markdown inline code not executed - r

I have an inline code enclosed with single backticks on a single line.
However,
The cohort had r echo = FALSE load("../data/cohort.rda") nrow(cohort) subjects.
is not executed and thus gives me this output in html and pdf:
The cohort had r echo = FALSE load("../data/cohort.rda") nrow(cohort) subjects.
I want this output: The cohort had 477 subjects.
When I exclude echo=FALSE, I get this message:
Quitting from lines 33-35 (Manuscript.Rmd)
Error in base::parse(text = code, srcfile = NULL) :
1:25: unexpected symbol
1: load("../data/cohort.rda") nrow
^
Calls: ... inline_exec -> withVisible -> eval -> parse_only ->
Execution halted

The inline R code needs to be a single R statement, which you can achieve by surrounding the entire code chunk with brackets {} and separating commands with semicolons. I saved a 3-row data frame named tmp to file tmp.rda, rendered an Rmd file with this line
There are `r {load("tmp.rda"); nrow(tmp)}` observations
and got the expected output.

Related

"Error in kmeans(na.omit(reduced_data_numeric, 5)) : 'centers' must be a number or a matrix" message when attempting to knit an Rmd as a HTML

I am presented with an error message when trying to knit an Rmd script. I have tried to drop any NA's from the data being used for lines 363-364 but this did not work. It is annoying because the k-means has been run and I have been able to plot using some simple code, but for some reason it won't knit. This was the original code that worked:
KM <- kmeans(reduced_data_numeric, 5)
Here is the Code I am trying to use in order for it to knit:
KM <- kmeans(na.omit(reduced_data_numeric, 5))
Here is the message shown in 'output' section when trying to render the HTML knit:
Quitting from lines 363-364 (Movies-Analysis.Rmd)
Error in kmeans(na.omit(reduced_data_numeric, 5)) :
'centers' must be a number or a matrix
Calls: <Anonymous> ... withVisible -> eval_with_user_handlers -> eval -> eval -> kmeans
You've included the number of centers as an argument for na.omit rather than kmeans.
Note where the parenthesis are at the end of this line and where the 5 is:
KM <- kmeans(na.omit(reduced_data_numeric), 5)

error in as.data.frame.default when knitting a r markdown file

When I run the following code chunk in r markdown, I get the expected outcome. However, when I tried knitting the file into html, an error message shows up. The data are from an excel file and I read the data using read.csv function.
Error message: error in as.data.frame.default (data, optional=True): can not coerce class "function" to a data.frame calls: ...terms.formula -> as.data.frame.default execution halted
total_steps <- aggregate(steps ~ date, data , sum)
total_steps

Reference variable name containing spaces within text in Rmarkdown [duplicate]

How can I include inline R code that refers to a variable name that contains spaces or other unusual characters (actual use-case is Pr(>F))? Backticks are the solution in plain R script, but they don't seem to work when the code is inline in a markdown doc. Here's an example:
```{r}
df <- data.frame(mydata= 1:10, yourdata = 20:29)
names(df) <- c("your data", "my data")
```
The first five values of your data are `r df$`your data`[1:5]`
Which when knitted gives:
Quitting from lines 7-9 (test-main.Rmd)
Error in base::parse(text = code, srcfile = NULL) :
2:0: unexpected end of input
1: df$
^
Calls: <Anonymous> ... <Anonymous> -> withVisible -> eval -> parse_only -> <Anonymous>
Execution halted
Note that this is different from showing the backticks. All I want to do is have the code executed when the the doc is knitted. My workaround is to assign the value of the odd-named variable to another object with a simple name in the chunk preceding the inline code. But I'm curious about how to directly call inline these objects with unusual names.
In this instance can use normal quotes,
The first five values of your data are `r df$"your data"[1:5]`
or rather
The first five values of your data are `r df[["your data"]][1:5]`

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)

How to include a line containing an error in R markdown

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)
```

Resources