gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:42:53 24 4
gpt4 key购买 nike

如何将 R 中的一列字符串表达式作为管道的一部分进行解析和求值?

在下面的例子中,我生成了我想要的列,evaluated。但我知道这不是正确的方法。我尝试采用 tidyverse 方法。但我只是很困惑。

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

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

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():

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

另一方面,我认为引用 @Martin Mächler 很重要。 :

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 - 解析和评估 R 中的字符串表达式列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57349214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com