3
votes

I'm looking to inline some R code into an essay I'm writing. The following is fine:

The quick brown fox jumped over \`r 2+2\` lazy dogs

The quick brown fox jumped over 4 lazy dogs

But when I try to combine dplyr with the following dataframe:

structure(list(name = structure(c(2L, 1L, 3L), .Label = c("Cat", 
"Dog", "Horse"), class = "factor"), n = c(4L, 3L, 8L)), .Names = c("name", 
"n"), class = "data.frame", row.names = c(NA, -3L))

it breaks:

The quick brown fox jumped over \`r as.numeric(temp %>% filter(name=="dog") %>% select(n)\` lazy dogs

Quitting from lines 80-81 (QuickBrown.Rmd)
Error in base::parse(text = code, keep.source = FALSE) : 
 <text>:2:0: unexpected end of input
1: as.numeric(temp %>% filter(name=="Dog") %>% select(
   ^

Trying to use the chunk objects gets me closer, especially with results="asis":

The quick brown fox jumped over 
```{r results="asis", echo=FALSE}
df <- as.numeric(temp %>% filter(name=="Dog") %>% select(n))
print(df[,1][[1]])
```
lazy dogs

The quick brown fox jumped over [1] 4 lazy dogs

but I can't work out how to get rid of the index number [1]. How can I best combine dplyr results inline with R Markdown or using the chunk, how can I get rid of the index number?

1
You might be able to use the cat function instead of print. Another option would be to use the chunk option to create a variable n and then call n inline like The quick brown fox jumped over 'r n' lazy dogs.tblznbits
ah, cat works, thanks. I take it inline dplyer is not possible though: The quick brown fox jumped over `r cat(as.numeric(temp %>% filter(name=="dog") %>% select(n))` lazy dogs still breakspluke

1 Answers

6
votes

I would try

```{r, echo=FALSE}
library(magrittr) # for %$% extraction
x <- temp %>% filter(name=="Dog") %>% slice(1) %$% n)
```

The quick brown fox jumped over `r x` lazy dogs


But you can also use dplyr inline. I tested this successfully:

---
title: "test"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(magrittr)
```

## R Markdown

here's a `r mtcars %>% slice(1) %$% gear` test with dplyr.