combine multiple expressions in R into one big expression -
i new r expression handling. stuck below problem. input appreciated.
i trying generate 2 individual equations , combine them 1 expression , pass algorithm find optimal value.
old_price elast units 1 59.98 1.3 151 2 59.98 1.3 230
code:
for(i in 1:nrow(df)){ o[i] = df$old_price[i] el[i] = df$elast[i] u[i] = df$units[i] assign(paste0("l",i),(substitute((x)*(1-(x-o)*el/o)*u, list(o=o[i],el=el[i],u=u[i])))) }
i able generate below 2 equations
l1 = (x) * (1 - (x - 59.98) * 1.3/59.98) * 151 l2 = (x) * (1 - (x - 59.98) * 1.3/59.98) * 230
and objective function this
eval_obj_f <- function(x){eval(l1)+eval(l2)}
i trying figure out how dynamically. if have different dataset of 4 observations, how can generate objective function below dynamically?
eval(l1)+eval(l2)+eval(l3)+eval(l4)
you need using real r expression
's , @ moment not expressions rather call
's. (check is.expression
or class
). don't name "df" dataframes since function name well, used "prdat":
o <- el <- u <- numeric(2) # if don't exist, loop errors out for(i in 1:nrow(prdat)){ o[i] = prdat$old_price[i] el[i] = prdat$elast[i] u[i] = prdat$units[i] assign(paste0("l",i), as.expression(substitute(x*(1-(x-o)*el/o)*u, list(o=o[i],el=el[i],u=u[i])))) } l1 #expression(x * (1 - (x - 59.98) * 1.3/59.98) * 151) # how expressions appear when printed. l2 #expression(x * (1 - (x - 59.98) * 1.3/59.98) * 230) exprlist <- list(l1,l2) eval_obj_f <- function(x){sum( sapply( exprlist, eval, envir=list(x=x) ) )} eval_obj_f(2) #[1] 1719.569
this seems pretty clunky. have apply
-ed function on dataframe , summed results. suppose might interesting attempt "compute on language"-approach, take alook @ code below think more in keeping "r-way". seems more compact ... , expressive:
func <- function(x) {apply(prdat, 1, function(z) x*(1- (x-z["old_price"])*z["elast"]/z["old_price"])*z["units"] )} > sum( func(x=2)) [1] 1719.569
this might better using code (but still lot more clunky second method imo):
exprvec <- expression() o <- el <- u <- numeric(2) for(i in 1:nrow(prdat)){ o[i] = prdat$old_price[i] el[i] = prdat$elast[i] u[i] = prdat$units[i] exprvec[[i]] <- substitute(x*(1-(x-o)*el/o)*u, list(o=o[i],el=el[i],u=u[i])) } #substitute-value gets coerced mode-expression # test > eval_obj_f <- function(x){sum( sapply( exprvec, eval, envir=list(x=x) ) )} > eval_obj_f(2) [1] 1719.569
Comments
Post a Comment