dot-dot-dot mechanism inside purrr functions

Viewed 267

Let me start with a toy dataset

library(magrittr)
library(purrr)
set.seed(13)
X<-matrix(rnorm(120),20,6) %>% data.frame %>% set_colnames(LETTERS[1:5])

and a toy function that draws 6 scatterplots: one for each column of X against random vector.

foo<-function(X){
  win.graph(5,5)
  par(mfcol=c(3,2))
  par(mar=c(5,4,.1,.1))
  X %>% iwalk(~plot(.x, rnorm(20), xlab=.y, ylab='Random'))
}

foo(X)

foo

Now I add dot-dot-dot mechanism to it:

foo<-function(X,...){
  win.graph(5,5)
  par(mfcol=c(3,2))
  par(mar=c(5,4,.1,.1))
  X %>% iwalk(~plot(.x, rnorm(20), xlab=.y, ylab='Random',...))
}

And now foo(X) results with an error Error in plot.window(...) : invalid 'xlim' value. Also foo(X, pch=2) gives the same error.

Why is that? Why iwalk seems to put any additional parameter passed via ... to xlim? How to change above code to be able to pass additional parameters via ...?

EDIT

I tried tidyeval approach with quos function and !!! operator:

foo<-function(X, ...){
  win.graph(5,5)
  par(mfcol=c(3,2))
  par(mar=c(5,4,.1,.1))
  vars<-quos(...)
  X %>% iwalk(~plot(.x, rnorm(20),xlab=.y, ylab='Random', !!! vars))
}

Now both foo(X) and foo(X, pch=2) result with Error in plot.xy(xy, type, ...) : invalid plot type...

1 Answers

We could do this do.call

foo <- function(X, ...){
     v1 <- c(...)

  win.graph(5,5)
  par(mfcol=c(3,2))
  par(mar=c(5,4,.1,.1))
   X %>%
      iwalk(~ {args <- list(xlab = .y, ylab = 'Random')
               args[names(v1)] <- v1
           do.call(plot, c(list(x = .x, y = rnorm(20)), args))            

               }) 
  }

foo(X)
foo(X, cex = 2)
foo(X, pch = 2)
foo(X, cex = 2, pch = 2)
foo(X, cex = 2, pch = 2, col = 2)

gives the output

enter image description here

Related