Home > Net >  Using the base R pipe to pipe ggplot2 to plotly
Using the base R pipe to pipe ggplot2 to plotly

Time:09-17

I can pipe from ggplot2 to plotly using:

library(tidyverse)
library(plotly)
diamonds %>%
  {ggplot(.,aes(carat, price))  
      geom_point()} |>
  ggplotly()

though I use the magrittr pipe and the base R pipe in the one chain.

Replacing the magrittr pipe with the base R pipe gives:

Error: function '{' not supported in RHS call of a pipe

Is there a way to just use the base R pipe?

I found R >4.1 syntax: Error: function 'function' not supported in RHS call of a pipe and https://github.com/plotly/plotly.R/issues/1229

Breaking the chain avoids the pipe issue:

p <- diamonds |>
  ggplot(aes(carat, price))  
  geom_point()
ggplotly(p)

CodePudding user response:

The native R pipe |> pipes the LHS into the first argument of RHS. It is important that you need to include the function as a function call, which means adding a () at the end of the function name. You can use the following code:

library(ggplot2)
library(plotly)
diamonds |> (\(.) {
  ggplot(., aes(carat, price))   geom_point()
  }) () |> ggplotly()

Created on 2022-09-17 with reprex v2.0.2

CodePudding user response:

Another option is

library(ggplot2)
library(plotly)
(diamonds |>
   ggplot(aes(carat, price))  
   geom_point()) |>
  ggplotly()
  • Related