代替R中的LHS [英] Substitute LHS of = in R

查看:325
本文介绍了代替R中的LHS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在R中的表达式中替换=的LHS。在我的个人情况下,我需要它来确保以下内容创建一个在数据框架中不存在的变量

  df%>%mutate(v = mean(w))

我尝试过 eval(substitute())但LHS未被替换



($)$($)$($)$($)$($)$($) b#同样在一个列表中
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

为什么't v replace throught eval / substitute?解决这个问题的最好办法是什么?

解决方案

1)eval / parse 创建一个 cmd string,解析它并评估它:

  f2<  - 函数(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)

  v1 v1_mean 
1 1 2
2 2 2
3 3 2
...等...

2)eval / as.call 另一种方法是构建列表,将其转换为调用并对其进行评估。 (这也是dplyr中 mutate_each_q 的方法。)

  f3<  - 函数(DF,x,env = parent.frame()){
L < - list(quote(mutate),.data = substitute(DF),quote(mean(v1)))
名称(L)[3]< - x
eval(as.call(L),env)
}

f3(DF,v1_name )

3)do.call 我们形成一个等于最后一个在以前的解决方案中列出两个组件,然后使用 do.call

  f3 < -  function(DF,x,env = parent.frame()){
L < - list(.data = substitute(DF),quote(mean(v1)))
名称(L)[2]< - x
do.call(mutate,L)
}

f3(DF,v1_name)

Upodate 添加了其他解决方案。


I would like to replace the LHS of "=" in a expression in R. In my personal case, I need it to make sure the following creates a variable that does not already exist in the data frame

df %>% mutate(v = mean(w))

I tried eval(substitute()) but the LHS is not substituted

eval(substitute(df %>% mutate(v = mean(w)), list(v = as.name("id"))))
 #similarly in a 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 the best way to work around it?

解决方案

1) eval/parse Create a cmd string, parse it and 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 Another way is to construct a list, convert it to a call and evaluate it. (This is also the approach that 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 We form a list equal to the last two components of the list in the prior solution and then 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.

这篇关于代替R中的LHS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆