Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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") 
    }
   )()

>Solution :

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")
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading