0

I created a function (inside a package) that uses the package "dplyr". I used roxygen2 to document my function and I included #' @import dplyr. Generally in my function I use dplyr::function when I am call a particular function from a package. However, I am not sure how to use a similar structure to stop this error:

Error in data %>% dplyr::group_by(dir.binned) %>% dplyr::summarise(count = n()) %>%  : 
  could not find function "%>%"

Code that is calling the error:

    T_data <- data %>%
  dplyr::group_by(dir.binned) %>%
  dplyr::summarise(count= n()) %>%
  dplyr::mutate(y = count/sum(count))

Does anyone know the best way to resolve this error?

Thanks!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
melmo
  • 757
  • 3
  • 15

1 Answers1

2

@import merely declares that you are importing a package, but does not make any names directly available (without explicitly qualifying its full name via pkg::name).

By contrast, @importFrom does make names directly available, and that’s what you need to use for operators. So, in front of your function using the pipe operator, write

#' @importFrom dplyr %>%

You could also import the pipe operator from the ‘magrittr’ package instead — that’s where ‘dplyr’ (currently) imports it from. However, this would add another direct dependency to your package, which goes against the idea of minimising a package’s dependencies as much as reasonably possible. True, your package currently (transitively) depends on ‘magrittr’ anyway, but if ‘dplyr’ ever decides to implement its own pipe operator (or import it from elsewhere), this transitive dependency will change.

Yet another way is to alias the operator in your own package:

`%>%` = dplyr::`%>%`

However, this only really makes sense if you intend to also re-export the operator.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214