解析和评估R中字符串表达式的列? [英] Parse and Evaluate Column of String Expressions in R?

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

问题描述

作为流水线的一部分,我如何解析和评估R中的一串字符串表达式?

How can I parse and evaluate a column of string expressions in R as part of a pipeline?

在下面的示例中,我生成了所需的列,即 evaluated .但是我知道这不是正确的方法.我尝试采取整洁的方法.但是我只是很困惑.

In the example below, I produce my desired column, evaluated. But I know this isn't the right approach. I tried taking a tidyverse approach. But I'm just very confused.

library(tidyverse)
df <- tibble(name = LETTERS[1:3], 
             to_evaluate = c("1-1+1", "iter+iter", "4*iter-1"), 
             evaluated = NA)
iter = 1
for (i in 1:nrow(df)) {
  df[i,"evaluated"] <- eval(parse(text=df$to_evaluate[[i]]))
}
print(df)
# # A tibble: 3 x 3
# name  to_evaluate evaluated
# <chr> <chr>           <dbl>
# 1 A     1-1+1               1
# 2 B     iter+iter           2
# 3 C     4*iter-1            3

作为管道的一部分,我尝试了:

As part of a pipeline, I tried:

df %>% mutate(evaluated = eval(parse(text=to_evaluate)))
df %>% mutate(evaluated = !!parse_exprs(to_evaluate))
df %>% mutate(evaluated = parse_exprs(to_evaluate))
df %>% mutate(evaluated = eval(parse_expr(to_evaluate)))
df %>% mutate(evaluated = parse_exprs(to_evaluate))
df %>% mutate(evaluated = eval(parse_exprs(to_evaluate)))
df %>% mutate(evaluated = eval_tidy(parse_exprs(to_evaluate)))

这些工作都没有.

推荐答案

您可以尝试:

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, ......).

这篇关于解析和评估R中字符串表达式的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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