r - (Pre)supply variables to function factory and within -
i'm reading through hadley's advanced r , trying stuff out. i'm trying create lazy closure function returns function supplied data.frame in environment using with , beingness able supply additional function arguments later.
lazy <- function(dataframe, x) { function(fun, x, ...) { with(dataframe, fun(x = x, ...)) } } lz_factory <- lazy(mtcars, "mpg") lz_factory(mean) lz_factory(cor, y="hp") so expecting dataframe part of function environment (a browser see confirms). however, variable name x not supply , can't supply new variable y when utilize cor first fun argument. has supplying character function (with) uses non-standard evaluation (nse). want uncle hadley proud of me rummaging eval, parse, substitute returned errors. means don't how r handling things. know why doesn't work (nse) not how create work. here's errors:
> lz_factory(mean) error in fun(x = x, ...) : argument "x" missing, no default > lz_factory(cor, y="hp") error in is.data.frame(x) : argument "x" missing, no default i thought tackle using substitute hadley shows here xyplot flop seen here:
lazy <- function(dataframe, default) { function(fun, x, ...) { if (missing(x)) x <- default eval(substitute(with(dataframe, fun(x, ...)))) } } lz_factory <- lazy(mtcars, "mpg") lz_factory(mean) lz_factory(cor, y="hp") > lz_factory(mean) [1] na warning message: in mean.default("mpg") : argument not numeric or logical: returning na > lz_factory(cor, y="hp") error in cor("mpg", y = "hp") : 'x' must numeric so how can create lazy function work it:
produces own function dataframe enclosed in environment allows me supply x if want , if not uses default supplied allows me pass unknown variables function createdlz_factory optimally i'd create function work with. if that's not possible it's nice know why. , lastly if not possible utilize with how can create function operational?
how function
lazy <- function(dataframe, ...) { pdots <- substitute(list(...)) if(is.null(names(pdots)) || names(pdots)[1]=="") { names(pdots)[2]<-"x" } function(fun, ...) { dots <- substitute(list(...))[-1] if (is.null(dots$x)) { dots$x <- pdots$x } with(dataframe, do.call(fun, as.list(dots))) } } this allows utilize names of variables in mtcars without quotes. example
lz_factory <- lazy(mtcars, mpg) lz_factory(mean) # [1] 20.09062 lz_factory(mean, x=hp) # [1] 146.6875 lz_factory(cor, y=hp) # [1] -0.7761684 here utilize bit of substituting create sure lazy evaluation , allow utilize variable names without quotes. with take care of evaluating expressions. i'm guessing there may way simplify this, @ to the lowest degree seems work.
r
No comments:
Post a Comment