2017-11-23 7 views
2

mich mit einem Spielzeug-Datensatz Beginnen wirPunkt-Punkt-Punkt-Mechanismus innerhalb purrr Funktionen

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

und ein Spielzeug-Funktion, die 6 Scatterplots zieht: eine für jede Spalte von X gegen Zufallsvektor.

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

Nun füge ich Punkt-Punkt-Punkt-Mechanismus, um es:

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',...)) 
} 

Und jetzt foo(X) Ergebnisse mit einem Fehler Error in plot.window(...) : invalid 'xlim' value. Auch foo(X, pch=2) gibt den gleichen Fehler.

Warum ist das? Warum scheint iwalk irgendeinen zusätzlichen Parameter zu setzen, der über ... an xlim übergeben wird? Wie kann der obige Code geändert werden, um zusätzliche Parameter über ... weiterzugeben?

EDIT

versuchte ich tidyeval Ansatz mit quos Funktion und !!! Betreiber:

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

beide Jetzt foo(X) und foo(X, pch=2) Ergebnis mit Error in plot.xy(xy, type, ...) : invalid plot type ...

Antwort

1

Wir werden diese do.call tun konnte

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) 

gibt dem Ausgang

enter image description here

+0

Vielen Dank für Ihre Lösung (+1). Es funktioniert jedoch, ich dachte an etwas, das "säuberlicher" ist. Bitte beachten Sie die Bearbeitung, die ich für meine Frage vorgenommen habe. –

Verwandte Themen