且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

解析和评估R中字符串表达式的列?

更新时间:2023-02-10 20:48:52

您可以尝试:

df %>%
 rowwise() %>%
 mutate(iter = 1,
        evaluated = eval(parse(text = to_evaluate))) %>%
 select(-iter)

  name  to_evaluate evaluated
  <chr> <chr>           <dbl>
1 A     1-1+1               1
2 B     iter+iter           2
3 C     4*iter-1            3

遵循此逻辑,其他可能性也可能起作用.使用 rlang :: parse_expr():

Following this logic, also other possibilities could work. Using rlang::parse_expr():

df %>%
 rowwise() %>%
 mutate(iter = 1,
        evaluated = eval(rlang::parse_expr(to_evaluate))) %>%
 select(-iter)

另一方面,我认为引用 @MartinMächler:

On the other hand, I think it is important to quote @Martin Mächler:

(可能)唯一的连接是通过parse(text = ....),一切都很好R程序员应该知道,这很少是一种有效或安全的方法表示构造表达式(或调用)的方法.而是了解更多有关replace(),quote()以及可能的使用权do.call(替代...).

The (possibly) only connection is via parse(text = ....) and all good R programmers should know that this is rarely an efficient or safe means to construct expressions (or calls). Rather learn more about substitute(), quote(), and possibly the power of using do.call(substitute, ......).