Search code examples
rdplyrtidyversemagrittrreprex

Why reprex cannot render %>% results


I have no problem making this tibble:

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

Which produce this:

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

But when I tried to wrap it with reprex

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

The clipboard showed this:

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

What's the right way to do it?


Solution

  • You should put package loading also into expression, otherwise the example is not reproducible:

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

    This will produce:

    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