patchwork icon indicating copy to clipboard operation
patchwork copied to clipboard

import individual operators or functions from patchwork

Open chunyunma opened this issue 5 years ago • 2 comments

This is a question rather than a bug report. I have been using import package which supports commands such as:

import::from(broom, tidy) import::from(magrittr, "%>%")

I tried to import a few operators/functions from patchwork using the similar method. I got an error message when I tried

import::from(patchwork, `-`)
# Error: '-' is not an exported object from 'namespace:patchwork

However, the next one was successful:

import::from(patchwork, `plot_layout`)

I am wondering if it is possible at all to import operators such as +, - from patchwork the same way I could with %>%?

Thank you very much!

chunyunma avatar Dec 22 '20 21:12 chunyunma

I am experiencing the same issue when trying to import a patchwork operator to a package namespace.

When I add the following line to the NAMESPACE file:

importFrom(patchwork, `/`)

I get this error when running devtools::check():

Error: object '/' is not exported by 'namespace: patchwork'

Thanks!

verasls avatar Dec 29 '20 02:12 verasls

The reason why you are experiencing difficulties is that you are trying to import an S3 method and not a function. In the NAMESPACE file of patchwork you can see that / is exported as a S3method: S3method("/",ggplot) unlike in magrittr where %>% is just a function (eg. in the NAMESPACE you will find export("%>%"))

In the advanced R book from Hadley in the chapter on S3 system you will find the following quote:

Unlike most functions, you can’t see the source code for most S3 methods just by typing their names. That’s because S3 methods are not usually exported: they live only inside the package and are not available from the global environment.

You are experiencing the same difficulties as this person on stack overflow: https://stackoverflow.com/questions/49319132/r-s3-method-not-exported-from-namespace

In order to make the S3 method available, you will need to load the patchwork package (either by import(patchwork) or loading a function via importFrom(patchwork,plot_layout)) which will make the S3 methods available in the methods table for that generic (here / in your case, which is an internal generic from the base package). This is also explained more clearly in the book R package on the chapter with NAMESPACE exports:

S3 methods always accompany the generic, so as long as you can access the generic (either implicitly or explicitly), the methods will also be available. In other words, you don’t need to do anything special for S3 methods. As long as you’ve imported the generic, all the methods will also be available.

ltuijnder avatar Aug 25 '21 13:08 ltuijnder