dplyr - Substitute LHS of = in R -
i replace lhs of "=" in expression in r. in personal case, need make sure following creates variable not exist in data frame
df %>% mutate(v = mean(w))
i tried eval(substitute())
lhs not substituted
eval(substitute(df %>% mutate(v = mean(w)), list(v = as.name("id")))) #similarly in list eval(substitute(l <- list(v=1:10),list(v=as.name("id")))) l $v [1] 1 2 3 4 5 6 7 8 9 10
why can't v
substituted throught eval/substitute? what's best way work around it?
1) eval/parse create cmd
string, parse , evaluate it:
f2 <- function(df, x, env = parent.frame()){ cmd <- sprintf("mutate(%s, %s = mean(v1))", deparse(substitute(df)), x) eval(parse(text = cmd), env) } f2(df, "v1_name")
giving
v1 v1_mean 1 1 2 2 2 2 3 3 2 ... etc ...
2) eval/as.call way construct list, convert call , evaluate it. (this approach mutate_each_q
in dplyr takes.)
f3 <- function(df, x, env = parent.frame()) { l <- list(quote(mutate), .data = substitute(df), quote(mean(v1))) names(l)[3] <- x eval(as.call(l), env) } f3(df, "v1_name")
3) do.call form list equal last 2 components of list in prior solution , use do.call
:
f3 <- function(df, x, env = parent.frame()) { l <- list(.data = substitute(df), quote(mean(v1))) names(l)[2] <- x do.call(mutate, l) } f3(df, "v1_name")
upodate added additional solutions.
Comments
Post a Comment