0

Inspired by the use of + operator by ggplot() and gganimate(), I was wondering how the + operator can be used for other use especially using it for strings like python.

I know I can overwrite these infix operators using `+` <- function(...) something but that completely overwrites the function, now I cannot use it for regular use like summing numbers.

Also I am more interested in knowing the internals i.e. how ggplot() managed to use + for their use without overwriting it. If anyone can explain it, I would be really thankful.

monte
  • 1,482
  • 1
  • 10
  • 26

2 Answers2

1

You can see how the + operator is implemented in ggplot by doing:

> ggplot2:::`+.gg`

function (e1, e2) 
{
    if (missing(e2)) {
        abort("Cannot use `+.gg()` with a single argument. Did you accidentally put + on a new line?")
    }
    e2name <- deparse(substitute(e2))
    if (is.theme(e1)) 
        add_theme(e1, e2, e2name)
    else if (is.ggplot(e1)) 
        add_ggplot(e1, e2, e2name)
    else if (is.ggproto(e1)) {
        abort("Cannot add ggproto objects together. Did you forget to add this object to a ggplot object?")
    }
}

You can see that this uses S3 class-based dispatch.

It is possible to do the same thing for character strings if you reclass them as a bespoke class with its own methods, as you can read about in this SO question

A minimal example of getting your own class to behave in an analogous fashion to ggplot would be something like:

`+.weirdclass` <- function(e1, e2) paste(e1, e2)

weirdclass <- function(x) structure(x, class = "weirdclass")

weirdclass("hello") +
  weirdclass("world")
#> [1] "hello world"
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
0

To concatenate strings in R, you can use either the paste()/paste0() base R functions or the str_c() function from the stringr package.

This post is also relevant to the ggplot2 part of your query: What is the difference between the "+" operator in ggplot2 and the "%>%" operator in magrittr?

huttoncp
  • 161
  • 4