r - Extract value from tibble in R markdown inline code
问题描述
I'm looking to access a value from a tibble using inline code in an R Markdown document.
The following code gives me a 1 x 2 tibble.
#library(tidyverse)
#library(knitr)
# Minimal working example
df <- tibble(
Event = c("Swimming","Swimming","Swimming","Camping","Hiking","Hiking")
)
df
# Creates 1 row x 2 column
df %>% count(Event) %>% slice(which.max(n))
If I create an object in a code chunk, I can select [1,1] and report that inline:
temp <- df %>% count(Event) %>% slice(which.max(n))
# The most popular event was `r temp[1,1]`.
# which becomes "The most popular event was Swimming."
Is there a way to do that within my dplyr pipes without creating a new object? Ideally, I would be able to do it all via inline code, something like:
`r df %>% count(Event) %>% slice(which.max(n)) %>% df[1,1]` # fails
Stepping back, I'm looking for a generalizable technique to use to select particular rows and cells from within a series of dplyr commands without creating new objects along the way.
解决方案
即使不在 R Markdown 中,您想要显示内联的代码行也不会运行,请在控制台中尝试。在管道中使用特殊运算符(如[
, [[
, )$
时,您需要以前缀而不是像其他函数那样的中缀形式指定它们,像这样。请注意您尝试的代码的比较,或者使用[[
向下钻取并仅选择文本而不是返回小标题。
library(tidyverse)
df <- tibble(
Event = c("Swimming","Swimming","Swimming","Camping","Hiking","Hiking")
)
df %>% count(Event) %>% slice(which.max(n)) %>% `[`(1,1)
#> # A tibble: 1 x 1
#> Event
#> <chr>
#> 1 Swimming
df %>% count(Event) %>% slice(which.max(n)) %>% `[[`("Event")
#> [1] "Swimming"
但是,这并不能完全解决您的问题,因为 R Markdown 使用反引号来表示内联代码,并且更改knitr
用于查找和评估内联代码的解析规则很复杂,因此这里它会认为代码以`[`
. 因此,您可以改为使用magrittr
这些函数的别名,extract
并extract2
在内联代码中:
Most popular event was `r df %>% count(Event) %>% slice(which.max(n)) %>% magrittr::extract2("Event")`
Most popular event was Swimming
在渲染的降价中正确打印。