问题
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:
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.
来源:https://stackoverflow.com/questions/37345268/inline-dplyr-in-r-markdown