R Markdown中的内联dplyr [英] inline dplyr in R Markdown
问题描述
我希望将一些R代码内联到我正在撰写的文章中。以下是很好的方法:
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
但是当我尝试将dplyr与以下数据框组合时:
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))
它会中断:
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(
^
尝试前往这些块对象使我离得更近,尤其是与result = asis:
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
快速的棕色狐狸跳过了[1] 4条懒狗
The quick brown fox jumped over [1] 4 lazy dogs
但是我不知道如何摆脱索引号[1]。如何最好地将dplyr结果与R Markdown内联或使用块进行最佳组合,如何摆脱索引号?
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?
推荐答案
我会尝试
```{r, echo=FALSE}
library(magrittr) # for %$% extraction
x <- temp %>% filter(name=="Dog") %>% slice(1) %$% n)
```
快速的棕色狐狸跳过了 rx懒狗
The quick brown fox jumped over `r x` lazy dogs
但是您也可以内联使用dplyr。我已成功测试了此内容:
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.
这篇关于R Markdown中的内联dplyr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!