passing ellipsis arguments to map function purrr package, R

后端 未结 3 1688
情歌与酒
情歌与酒 2020-12-19 14:55

I want to use ellipsis parameters inside map function of purrr package. this is a toy example:

f1<-function(x,a=NA,b=NA,prs=seq(0, 1, 0.25),SW=T){
  if(SW         


        
3条回答
  •  一个人的身影
    2020-12-19 15:53

    MrFlick solution did not work for me: I think indeed you also need to pass the ... to the anonymous function, which then requires using function(x,...) instead of ~ (as suggested by @dmi3kno).

    That means you need the quite surprising triple ... call:

    map(x, function(x, ...) mean(x, trim=0, ...), ...)
    

    Example:

    library(purrr)
    x <- list(c(1,2), c(1,2,NA))
    fo1 <- function(...) map(x, ~mean(., trim=0, ...), ...)
    fo2 <- function(...) map(x, function(x, ...) mean(x, trim=0, ...), ...)
    
    fo1()
    #> Warning in if (na.rm) x <- x[!is.na(x)]: the condition has length > 1 and only
    #> the first element will be used
    
    #> Warning in if (na.rm) x <- x[!is.na(x)]: the condition has length > 1 and only
    #> the first element will be used
    #> [[1]]
    #> [1] 1.5
    #> 
    #> [[2]]
    #> [1] 1.5
    
    fo2()
    #> [[1]]
    #> [1] 1.5
    #> 
    #> [[2]]
    #> [1] NA
    fo2(na.rm=TRUE)
    #> [[1]]
    #> [1] 1.5
    #> 
    #> [[2]]
    #> [1] 1.5
    

    Created on 2020-11-16 by the reprex package (v0.3.0)

提交回复
热议问题