Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
817 views
in Technique[技术] by (71.8m points)

passing ellipsis arguments to map function purrr package, R

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){
    res<-data.frame(name1=a,name2=b,t(quantile(x, prs, na.rm = T)),  mean=mean(x, na.rm = T), sd=sd(x, na.rm = T),
                    NAs=length(x[is.na(x)]),n=length(x[!is.na(x)]),SWp=shapiro.test(x)$p.value,stringsAsFactors =F)
  }else
  {
    res<-data.frame(name1=a,name2=b,t(quantile(x, prs, na.rm = T)),  mean=mean(x, na.rm = T), sd=sd(x, na.rm = T),
                    NAs=length(x[is.na(x)]),n=length(x[!is.na(x)]),stringsAsFactors =F)
  }
return(res)
}

f1(c(NA,rnorm(25),NA),SW=F)
f1(c(NA,rnorm(25),NA))

now I want to use f1 inside another function f2:

f2<-function(df,...){
  res<-map_df(colnames(df),~f1(df[,.],a=.,...))
  return(res)
}

where ... is intended mainly to manipulate SW and a or b parameters in f1 function. however f2 is not doing what I want as can be seen here

f2(iris[,-5])
f2(iris[,-5],SW=F)

I appreciate any guide in how to use addecuatelly ... inside map

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just need to pass the ellipses through the map_df() call as well. Otherwise they can't get into the inner f1() call.

f2 <- function(df, ...){
  res <- map_df(colnames(df), ~f1(df[,.], a=., ...), ...)
  return(res)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...