Home > database >  Piping data to plot and points function in base R with `|>`
Piping data to plot and points function in base R with `|>`

Time:09-14

I'm wondering how to pipe data to make a plot and add points with the native R pipe operator |>

dtf = data.frame(pop1 = 1:10, pop2 = 2:11, gen = 1:10)
dtf |>
  (\(dt) plot(x = dt[,"gen"], y = dt[,"pop1"]))() |>
  (\(dt) points(x = dt[,"gen"], y = dt[,"pop2"]))() 

The lines below work:

dtf |>
      (\(dt) plot(x = dt[,"gen"], y = dt[,"pop1"]))()

But when adding the points, R 'forgot' that it was piping the data since there is no output from plot to pass it to points. Is there a way to 'continue' the pipe to feed the points function?

I figured out that this would work, but kind of misses the purpose of the pipe operator:

dtf |>
  (function(dt) {
    plot(x = dt[,"gen"], 
         y = dt[,"pop1"], pch = 19, col = "red")
    points(x = dt[,"gen"], 
           y = dt[,"pop2"], pch = 19, col = "black") 
    }
   )()

CodePudding user response:

The pipe operator is supposed to make code simpler and easier to read, but when working with functions like plot() and points() that aren't designed with piping in mind, it tends to make things more obscure. You're better off just using functions like that in separate statements:

plot(pop1 ~ gen, pch = 19, col = "red", data = dtf)
points(pop2 ~ gen, pch = 19, col = "black", data = dtf)

or

with(dtf, {
  plot(pop1 ~ gen, pch = 19, col = "red")
  points(pop2 ~ gen, pch = 19, col = "black")
})
  •  Tags:  
  • r
  • Related