Home » R » ggplot2 » Using ggplot2 in a package

Using ggplot2 in a package

Due to my recent conversion to ggplot2, I am starting to use ggplot() in packages. Running R CMD check on this function

    ggplot(data=data.frame(n=1:n,v=object@vars),
           aes(x=n,y=v))

I got the note

* checking R code for possible problems ... NOTE
colocpc.plot: no visible binding for global variable ‘v’

It turns out this is a known feature of the R checking code. v is indeed undefined. I like a clean run of R CMD check --as-cran for all packages. The link gives a discussion of alternative work-arounds:

  • give v a dummy value before the call to ggplot(), ie
v <- NULL
  • wrap the call to ggplot() in with(), ie
df <- data.frame(n=1:n,v=object@vars)
with(df, ggplot(data=df, aes(x=n, y=v)))
  • use aes_string() in place of aes(), ie
    ggplot(data.frame(n=1:n,v=object@vars),
           aes_string(x = 'n', y = 'v') # to get around R CMD check complaining about next line
                                        # aes(x=n,y=v)
           )

I have gone for the last option, because it leaves the code more readable, but it means either I need to adopt using aes_string() in all my code, or I need to remember to convert from aes() every time I package up my functions. No workaround is ever perfect.

Advertisements

One thought on “Using ggplot2 in a package

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s