评估data.table中的表达式 [英] evaluate expression in data.table

查看:41
本文介绍了评估data.table中的表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串作为公式求值:

I'm trying to evaluate a string as a formula:

在dplyr中,它看起来像这样:

In dplyr it would look like this:

dt = data.table(a = 1:10)
expr = 'sum(a)'

dt %>% 
  mutate(b := !!parse_expr(expr))

但是,当我尝试使用data.table时,出现了错误:

However when I try with data.table I'm getting an error:

dt[, b := parse_expr(expr)]

[.data.table (dt,,:= (b,parse_expr(expr)))中的错误:RHS分配不是NULL,不是原子向量(请参见?is.atomic),也不是列表列.

Error in [.data.table(dt, , :=(b, parse_expr(expr))) : RHS of assignment is not NULL, not an an atomic vector (see ?is.atomic) and not a list column.

推荐答案

代替 parse_expr ,可以使用 eval(parse

dt[, b := eval(parse(text = expr))]

或者在 parse_expr 上用 eval 包装,因为 !! tidyverse

Or wrap with eval on parse_expr as the !! is doing the evaluation in tidyverse

dt[, b := eval(rlang::parse_expr(expr)) ]

这篇关于评估data.table中的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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