intelligently using the ellipsis in an R function -
i had function signature this:
myfunction=function(class="class",v1='y',v2='y',dfparam=df){
where df
dataframe , assumed there attribute called class
in df. wanted make more general can accept variety of dataframes, df, not 1 has attribute called class. added in classname
parameter , classvalue
parameter replace class parameter. also, want allow unlimited arguments v1, v2, v3 etc. , using elipsis this:
myfunctiongeneral = function(classname="class", classvalue="democrat", dfparam=df, ...){ arguments <- list(...)
prior using elipsis, had line used arguments follows:
x_bool=dfparam$v1==v1 & dfparam$v2==v2
i started out doing this:
x_bool=dfparam[,2]==arguments[1] & dfparam[,3]==arguments[2]
but want unlimited number of possible paremeters in elipsis. need expand statement somehow unraveling ellipsis. here example:
install.packages("vcd") library(vcd) data(arthritis) aar=arthritis[,-c(1,4)] myfunctiongeneral=function(classname="class",classvalue="democrat",dfparam=df, ...){ dfparam$names<-rownames(dfparam) arguments<-list(...) dfparamdroppedclass=dfparam[,-1] #x_bool=dfparam[,2]==arguments[1] & dfparam[,3]==arguments[2] x_bool=do.call(all, map("==", dfparamdroppedclass, arguments)) x=dfparam[x_bool,] }
this should illustrate principle:
arguments <- list(1, 2, 3) params <- list(1, 2, 3) do.call(all, map("==", arguments, params)) #[1] true params <- list(1, 2, 4) do.call(all, map("==", arguments, params)) #[1] false
all equivalent arbitrary number of &
, , map
iterates ==
on 2 lists.
edit: apparently data.frame has more 1 observation. can't use all
, need use reduce
in reduce("&", map("==", arguments, params))
. example:
myfunctiongeneral=function(classname="class",classvalue="democrat",dfparam=df, ...){ dfparam$names<-rownames(dfparam) arguments<-list(...) dfparamdroppedclass=dfparam[, -c(1, 4)] #x_bool=dfparam[,2]==arguments[1] & dfparam[,3]==arguments[2] x_bool=reduce("&", map("==", dfparamdroppedclass, arguments)) dfparam[x_bool,] } myfunctiongeneral('treatment','placebo',aar,'male','marked') # treatment sex improved names #4 treated male marked 4 #5 treated male marked 5 #6 treated male marked 6 #8 treated male marked 8 #14 treated male marked 14 #52 placebo male marked 52
Comments
Post a Comment