为什么 reprex 无法呈现 %>% 结果

Why reprex cannot render %>% results

我做这个小问题没问题:

library(dplyr)
library(tibble)
as.tibble(mtcars[2:3,2:3]) %>% mutate(cyl_x_disp = cyl * disp)

产生这个:

# A tibble: 2 × 3
    cyl  disp cyl_x_disp
  <dbl> <dbl>      <dbl>
1     6   160        960
2     4   108        432

但是当我尝试用 reprex

包装它时
reprex::reprex(as.tibble(mtcars[2:3,2:3]) %>% mutate(cyl_x_disp = cyl * disp))

剪贴板显示如下:

as.tibble(mtcars[2:3, 2:3]) %>% mutate(cyl_x_disp = cyl * disp)
#> Error in eval(expr, envir, enclos): could not find function "%>%"

正确的做法是什么?

你应该把包加载也放在表达式中,否则这个例子是不可重现的:

reprex::reprex({
    library(tibble)
    library(dplyr)
    as.tibble(mtcars[2:3,2:3]) %>% mutate(cyl_x_disp = cyl * disp)
})

这将产生:

library(tibble)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
as.tibble(mtcars[2:3, 2:3]) %>% mutate(cyl_x_disp = cyl * disp)
#> # A tibble: 2 × 3
#>     cyl  disp cyl_x_disp
#>   <dbl> <dbl>      <dbl>
#> 1     6   160        960
#> 2     4   108        432